dsPIC30F Embedded Encryption Libraries User's Guide - Microchip

Oct 31, 2005 - Control Solutions Company are registered trademarks of. Microchip Technology ..... General Technical Support – Frequently Asked Questions (FAQs), technical support requests ... REVISION HISTORY ...... Philippines - Manila.
1MB taille 17 téléchargements 267 vues
dsPIC30F Embedded Encryption Libraries User’s Guide

© 2006 Microchip Technology Inc.

DS51468B

Note the following details of the code protection feature on Microchip devices: •

Microchip products meet the specification contained in their particular Microchip Data Sheet.



Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.



There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.



Microchip is willing to work with the customer who is concerned about the integrity of their code.



Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”

Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.

Information contained in this publication regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer’s risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.

Trademarks The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KEELOQ, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, PICMASTER, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Linear Active Thermistor, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, Real ICE, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and Zena are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. © 2006, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved. Printed on recycled paper.

Microchip received ISO/TS-16949:2002 quality system certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona and Mountain View, California in October 2003. The Company’s quality system processes and procedures are for its PICmicro® 8-bit MCUs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.

DS51468B-page ii

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Table of Contents Preface ..................................................................................................................1 Chapter 1. Introduction 1.1 Introduction .................................................................................................... 7 1.2 Highlights ....................................................................................................... 7 1.3 Overview of Embedded Cryptographic Applications ...................................... 7 1.4 Using the dsPIC DSC Devices in Embedded Cryptographic Applications ..... 8 1.5 dsPIC30F Embedded Encryption Libraries .................................................... 8

Chapter 2. dsPIC30F Symmetric Key Embedded Encryption Library 2.1 Introduction .................................................................................................... 9 2.2 Highlights ....................................................................................................... 9 2.3 Library Software Contents .............................................................................. 9 2.4 Using the Library .......................................................................................... 10

Chapter 3. Symmetric Key Encryption Utilities 3.1 Introduction .................................................................................................. 13 3.2 Highlights ..................................................................................................... 13 3.3 Encrypting Messages: Modes of Operation and Padding ............................ 13 3.4 Message Authentication Modes ................................................................... 18 3.5 Combined Message Authentication and Encryption Modes ......................... 19 3.6 Symmetric Key Encryption/Decryption Functions ........................................ 20

Chapter 4. dsPIC30F Asymmetric Key Embedded Encryption Library 4.1 Introduction .................................................................................................. 43 4.2 Highlights ..................................................................................................... 43 4.3 Library Software Contents ............................................................................ 43 4.4 Using the Library .......................................................................................... 44

Chapter 5. Asymmetric Key Encryption Utilities 5.1 Introduction .................................................................................................. 47 5.2 Highlights ..................................................................................................... 47 5.3 General Primer on Asymmetric Functions ................................................... 47 5.4 Specific Public Key Algorithms ..................................................................... 51 5.5 Asymmetric Key Functions ........................................................................... 54

Chapter 6. Hash and Auxiliary Functions 6.1 Introduction .................................................................................................. 67 6.2 Highlights ..................................................................................................... 67 6.3 Message Digest/Hash Functions ................................................................. 67 6.4 Auxiliary Functions ....................................................................................... 70

© 2006 Microchip Technology Inc.

DS51468B-page iii

dsPIC30F Embedded Encryption Libraries User’s Guide Appendix A. Symmetric Function Examples A.1 Introduction .................................................................................................. 75 A.2 Highlights ..................................................................................................... 75 A.3 Symmetric Function Examples .................................................................... 75

Appendix B. Asymmetric Function Examples B.1 Introduction ................................................................................................ 107 B.2 Highlights ................................................................................................... 107 B.3 Asymmetric Function Examples ................................................................ 107

Appendix C. Hash and Auxiliary Function Examples C.1 Introduction ................................................................................................ 125 C.2 Highlights ................................................................................................... 125 C.3 Hash and Auxiliary Function Examples ..................................................... 125

Appendix D. References D.1 Introduction ................................................................................................ 131 D.2 Highlights ................................................................................................... 131 D.3 References to Federal Information Processing Standards (FIPS) and Other Specifications ...................................................................... 131 D.4 References to Textbooks on Modern Cryptographic Practices and Algorithms ...................................................................................... 132

Appendix E. Asymmetric Key Embedded Encryption Library Errata E.1 Errata ......................................................................................................... 133

Worldwide Sales and Service .........................................................................136

DS51468B-page iv

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Preface INTRODUCTION This preface contains general information that will be useful to know before either reading the remainder of this user guide or using the dsPIC30F Symmetric Key and Asymmetric Key Embedded Encryption Libraries.

HIGHLIGHTS Items discussed in this chapter are: • • • • • • •

About this Guide Warranty Registration Recommended Reading Troubleshooting The Microchip Web Site Development Systems Customer Notification Service Customer Support

ABOUT THIS GUIDE This document describes the usage of the following dsPIC30F software libraries: • dsPIC30F Symmetric Key Embedded Encryption Library • dsPIC30F Asymmetric Key Embedded Encryption Library The information in this document is useful when writing C or assembly code for dsPIC® DSC applications that employ the two libraries. For a detailed discussion about MPLAB® C30 compiler operation and functions, refer to the “MPLAB C30 User’s Guide” (DS51217).

Document Layout The Reference Guide layout is as follows: • Chapter 1: Introduction – This chapter introduces security-related applications and provides top-level guidance on the use of various functions. • Chapter 2: dsPIC30F Symmetric Key Embedded Encryption Library – This chapter discusses the contents of the dsPIC30F Symmetric Key Embedded Encryption Library archive file and its usability with the dsPIC DSC development tools. • Chapter 3: Symmetric Key Encryption Utilities – This chapter describes the API for symmetric key encryption and decryption functions and various modes of operation available to the AES and Triple-DES functions in the dsPIC30F Symmetric Key Embedded Encryption Library. • Chapter 4: dsPIC30F Asymmetric Key Embedded Encryption Library – This chapter discusses the contents of the dsPIC30F Asymmetric Key Embedded Encryption Library archive file and its usability with the dsPIC DSC development tools.

© 2006 Microchip Technology Inc.

DS51468B-page 1

dsPIC30F Embedded Encryption Libraries User’s Guide • Chapter 5: Asymmetric Key Encryption Utilities – This chapter describes the API for asymmetric key encryption, signing, verification and key agreement functions in the dsPIC30F Asymmetric Key Embedded Encryption Library. It discusses RSA, Diffie-Hellman and DSA functions. • Chapter 6: Hash and Auxiliary Functions – This chapter describes the API for hash (message digests) and random number generator functions available in both the dsPIC30F Embedded Encryption Libraries. • Appendix A: Symmetric Function Examples – This appendix contains code examples, written in C, demonstrating how the Symmetric Key encryption/ decryption functions may be used. • Appendix B: Asymmetric Function Examples – This appendix contains code examples, written in C, demonstrating how the Asymmetric Key encryption/ decryption functions may be used. • Appendix C: Hash and Auxiliary Function Examples – This appendix contains code examples, written in C, demonstrating how the Hash and Auxiliary functions may be used. • Appendix D: References – This chapter lists several popular texts and US governmental standards that help in understanding how the library functions operate and where they may be employed. • Appendix E: Asymmetric Key Embedded Encryption Library Errata – This appendix provides information regarding specific dsPIC30F devices and the Big Integer Arithmetic Package.

Conventions Used in this Guide This manual uses the following documentation conventions: TABLE 1: DOCUMENTATION CONVENTIONS Description

Represents

Examples

Italic characters

Referenced books.

MPLAB User’s Guide

Courier Font

User entered or sample source code in C or assembly language

#define ENIGMA

0xnnnn

0xnnnn represents a hexadecimal number where n is a hexadecimal digit

0xFFFF, 0x007A

Documentation Updates All documentation becomes dated, and this user’s guide is no exception. Since dsPIC30F Symmetric Key and Asymmetric Key Embedded Encryption Libraries and other Microchip tools are constantly evolving to meet customer needs, some library and/or precompiled object file descriptions may differ from those in this document. Please refer to our web site to obtain the latest documentation available.

Documentation Numbering Conventions Documents are numbered with a “DS” number. The number is located on the bottom of each page, in front of the page number. The numbering convention for the DS Number is: DSXXXXXA, where:

DS51468B-page 2

XXXXX

=

The document number.

A

=

The revision level of the document.

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library WARRANTY REGISTRATION Please complete the enclosed Warranty Registration Card and mail it promptly. Sending in your Warranty Registration Card entitles users to receive new product updates. Interim software releases are available at the Microchip web site.

RECOMMENDED READING This user’s guide describes the Application Package Interface (API) for the dsPIC30F Symmetric Key and Asymmetric Key Embedded Encryption Libraries. This guide also provides several code examples to demonstrate the usage of the library functions. Cryptographic Reference Guides This manual assumes that users are familiar with basic cryptographic algorithms and concepts as well as the use of these primitives to build a secure system. Many excellent books have been written on these topics and should be consulted for general use of cryptographic algorithms. A list of reference books and US governmental standards is provided in the References appendix. MPLAB® C30 C Compiler User’s Guide (DS51284) Comprehensive guide that describes the usage, operation and features of Microchip’s MPLAB C30 C compiler. MPLAB® IDE Quick Start Guide (DS51281) Describes how to set up the MPLAB IDE software and use it to create projects and program devices. MPASM™ Assembler, MPLINK™ Object Linker, MPLIB™ Object Librarian User’s Guide (DS33014) This user’s guide describes how to use the Microchip PICmicro® MCU MPASM assembler, the MPLINK object linker and the MPLIB object librarian.

Microchip Web Site The Microchip web site (www.microchip.com) contains a wealth of documentation. Individual data sheets, application notes, tutorials and user’s guides are all available for easy download. All documentation is in Adobe® Acrobat® (PDF) format.

TROUBLESHOOTING See the README files for information on common problems not addressed in the “dsPIC30F Embedded Encryption Libraries User’s Guide”.

© 2006 Microchip Technology Inc.

DS51468B-page 3

dsPIC30F Embedded Encryption Libraries User’s Guide THE MICROCHIP WEB SITE Microchip provides online support via our web site at www.microchip.com. This web site is used as a means to make files and information easily available to customers. Accessible by using your favorite Internet browser, the web site contains the following information: • Product Support – Data sheets and errata, application notes and sample programs, design resources, user’s guides and hardware support documents, latest software releases and archived software • General Technical Support – Frequently Asked Questions (FAQs), technical support requests, online discussion groups, Microchip consultant program member listing • Business of Microchip – Product selector and ordering guides, latest Microchip press releases, listing of seminars and events, listings of Microchip sales offices, distributors and factory representatives

DS51468B-page 4

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library DEVELOPMENT SYSTEMS CUSTOMER NOTIFICATION SERVICE Microchip’s customer notification service helps keep customers current on Microchip products. Subscribers will receive e-mail notification whenever there are changes, updates, revisions or errata related to a specified product family or development tool of interest. To register, access the Microchip web site at www.microchip.com, click on Customer Change Notification and follow the registration instructions. The Development Systems product group categories are: • Compilers – The latest information on Microchip C compilers and other language tools. These include the MPLAB C18 and MPLAB C30 C compilers; MPASM and MPLAB ASM30 assemblers; MPLINK and MPLAB LINK30 object linkers; and MPLIB and MPLAB LIB30 object librarians. • Emulators – The latest information on Microchip in-circuit emulators.This includes the MPLAB ICE 2000 and MPLAB ICE 4000. • In-Circuit Debuggers – The latest information on the Microchip in-circuit debugger, MPLAB ICD 2. • MPLAB IDE – The latest information on Microchip MPLAB IDE, the Windows® Integrated Development Environment for development systems tools. This list is focused on the MPLAB IDE, MPLAB IDE Project Manager, MPLAB Editor and MPLAB SIM simulator, as well as general editing and debugging features. Programmers – The latest information on Microchip programmers. These include the MPLAB PM3 and PRO MATE® II device programmers and the PICSTART® Plus and PICkit™ 1development programmers.

© 2006 Microchip Technology Inc.

DS51468B-page 5

dsPIC30F Embedded Encryption Libraries User’s Guide CUSTOMER SUPPORT Users of Microchip products can receive assistance through several channels: • • • •

Distributor or Representative Local Sales Office Field Application Engineer (FAE) Technical Support

Customers should contact their distributor, representative or field application engineer (FAE) for support. Local sales offices are also available to help customers. A listing of sales offices and locations is included in the back of this document. Technical support is available through the web site at: http://support.microchip.com

REVISION HISTORY Rev A Document (04/2004) First revision of this document. Rev B Document (01/2006) Added Appendix E.

DS51468B-page 6

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Chapter 1. Introduction 1.1

INTRODUCTION This chapter provides an introduction to the dsPIC30F Symmetric Key and Asymmetric Key Embedded Encryption Libraries.

1.2

HIGHLIGHTS This chapter is organized as follows: • Overview of Embedded Cryptographic Applications • Using dsPIC DSC Devices in Embedded Cryptographic Applications • dsPIC30F Embedded Encryption Libraries

1.3

OVERVIEW OF EMBEDDED CRYPTOGRAPHIC APPLICATIONS A number of embedded applications involve monitoring and communicating data. Often, a microcontroller used in such applications finds itself privy to information that may be sensitive in nature. For example, assume a microcontroller is used in monitoring the number of currency notes that exist in an ATM machine. When the number of currency notes in the machine reaches a critical minimum, the microcontroller uses a telephone line to connect and communicate to a parent bank, that the ATM machine will soon require additional currency notes for performing daily transactions. Based on the information received at the bank, additional currency notes are routed to the ATM machine. A number of security threats exist in this scenario. A few are presented below: • A “snooper” system may be “listening” to information on the telephone line connected to the ATM machine. If the ATM machine sends out “plain text” messages (i.e., messages that are not encrypted) to the bank, the snooper system may be able to use the information for fraudulent motives. • Another system may pretend to be an ATM machine, and may send messages to the bank requesting additional currency notes. The example presented above may be easily extended to any number of applications that monitor data in one way or another. The need for a secure means of communication with the embedded application deployed on the field is obvious. It is also desirable to create a security infrastructure without adding to the cost of the deployed application. From a cost of goods perspective, in the example of the ATM-bank communication, it may be desirable to add high security infrastructure at the bank-end of the communication channel rather than the ATM-end of that channel, since there is only one bank while there are many ATM machines. The infrastructure would include secure servers and large databases that store information that identifies each ATM machine that the bank may receive messages from. On the ATM-end of the communication channel, it may be more desirable to simply add security into the microcontroller in the form of application software. This ensures that the ATM machine costs remain the same, while the microcontroller within it has added value, since it now performs dual functions of data encryption as well as monitoring currency notes within the ATM machine. Further, the data is encrypted at its very origin since the microcontroller is responsible for data acquisition functions.

© 2006 Microchip Technology Inc.

DS51468B-page 7

dsPIC30F Embedded Encryption Libraries User’s Guide Some other examples where data security, may be very useful are listed below: • Point-Of-Sale Terminals that communicate with servers to update sales of stocked merchandise. • Intruder-Alert Systems in houses and automobiles that communicate with public security agencies. • Wireless and Hand-Held Devices that need to interact with secure servers or other access-controlled network devices.

1.4

USING THE dsPIC DSC DEVICES IN EMBEDDED CRYPTOGRAPHIC APPLICATIONS From the examples presented in Section 1.3 “Overview of Embedded Cryptographic Applications”, microcontrollers may seem an ideal and likely candidate for deploying into applications where data security is essential. However, there are not many microcontrollers that satisfactorily respond to the need for data security. The dsPIC30F family of 16-bit microcontrollers may be effectively used in securing data in various applications. Some of the key features that enable the dsPIC30F processor family, in such applications, are: • Encrypting/Decrypting information requires complex mathematical calculations. The dsPIC30F features a DSP engine that performs fast computations, thus providing a high data rate. • The dsPIC30F features various communication peripherals (SPI, UART, CAN, Codec Interface and I2C™) and a 16-bit bidirectional port. These are useful in transmitting data to the external world at high speeds. • The dsPIC30F features various other peripherals like A/D converters, Codec interface, external interrupt pins, timers, PWMs etc., that already make it the microcontroller of choice in sensor, modem, telephony and speech applications. • The dsPIC30F features a reliable scheme to code-protect and optionally write-protect the on-chip Flash memory • Microchip offers a reliable set of embedded encryption libraries to perform various encryption, authentication, signing and verification functions.

1.5

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES The dsPIC30F cryptographic libraries are offered in two software packages. These are: • dsPIC30F Symmetric Key Embedded Encryption Library This library contains implementations of the Advanced Encryption Standard (AES), Triple Data Encryption Algorithm (popularly Triple DES), Secure Hash Algorithm (SHA-1), Message Digest Algorithm (MD5) and the ANSI X9.82 Deterministic Random Bit Generator algorithm. • dsPIC30F Asymmetric Key Embedded Encryption Library This library contains implementations of Rivest Shamir Adleman (RSA) algorithm, Digital Signature Algorithm (DSA) and Diffie Hellman Key Agreement Protocol. Each library is provided with header files, build-scripts and extensive examples of use. The two libraries were developed in assembly language and are completely callable by C programs. The libraries have been optimized for speed of execution as well as memory size, in that order. The libraries use minimal RAM space. Through the remainder of this user guide, we will describe in detail, the features and the library functions of the embedded encryption libraries, as well as provide code examples of their use.

DS51468B-page 8

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Chapter 2. dsPIC30F Symmetric Key Embedded Encryption Library 2.1

INTRODUCTION This chapter provides information required to begin using the dsPIC DSC Symmetric Key Embedded Encryption Library. Chapter 3. “Symmetric Key Encryption Utilities”, provides information on operational aspects of the symmetric key encryption and decryption functions packaged in this library. Chapter 6. “Hash and Auxiliary Functions”, provides information on operational aspects of hash functions and random number generators provided in this library.

2.2

HIGHLIGHTS This chapter covers the following topics: • Library Software Contents • Using the Library • Rebuilding the Library

2.3

LIBRARY SOFTWARE CONTENTS Upon installation of the library, the following files and folders will be extracted under the folder named “dsPICSymCryptoLib”: • doc This folder contains this User’s Guide document in PDF format. • lib This folder contains the pre-compiled library archive file named “libSymCrypto.a” that includes all of the object files for the sources used to build the library. Another file, “libSymCryptoSmall.a” has also been provided and is described in Section 2.4.1 “Building Applications with the Library”. • include\c This folder contains C header files for each object file within the library archive. • include\asm This folder contains assembler include files for each object file within the library archive file. • examples This folder contains various code examples in C that demonstrate library usage. Please read the “readme.txt” file provided with the release version of your library for further details. This file resides in the “dsPICSymCryptoLib” folder. The dsPIC30F Symmetric Key Embedded Encryption Library archive contains pre-compiled object files created by assembling the source files. The code size (in bytes) for each object file is provided in Table 2-1. An object file is linked into an application only once, even if multiple functions from this object file are invoked. Further, if any object files are unused, they will not be linked into the application, though they are present in the library archive file.

© 2006 Microchip Technology Inc.

DS51468B-page 9

dsPIC30F Embedded Encryption Libraries User’s Guide TABLE 2-1: Algorithm

SYMMETRIC LIBRARY COMPOSITION

Advanced Encryption Basic Encryption Function Standard (AES) Basic Decryption Function Electronic Code Book Mode Cipher Block Chaining Encryption and Message Authentication (CBC-MAC) Mode CBC Mode Decryption Counter Mode Combined CBC MAC and Counter Mode Triple Data Basic Encryption and Encryption Algorithm Decryption Functions (Triple DES) Electronic Code Book Mode Cipher Block Chaining Mode Counter Mode Secure Hash SHA-1 Algorithm (SHA-1) Message Digest MD5 Algorithm (MD5) ANSI X9.82 Deterministic Random Bit Generator

2.4

Object File

Size in Bytes

aes_encrypt.o aes_decrypt.o aes_ecb.o aes_cbc_encrypt_and_mac.o

2505 2895 234 663

aes_cbc_decrypt.o aes_ctr.o aes_ccm.o

357 348 930

tdes.o

8892

tdes_ecb.o tdes_cbc.o tdes_ctr.o sha1.o

120 903 348 909

md5.o

1428

drbg.o

441

Library Functions

USING THE LIBRARY 2.4.1

Building Applications with the Library

Building an application which utilizes this library typically requires three files. These are: • The pre-compiled library archive file, “libSymCrypto.a”. Another library file, "libSymCryptoSmall.a", has also been provided. This file contains all the functions except SHA-1, MD5 and the DRBG (X9.82). This file is provided to enable interoperability with the dsPIC30F Asymmetric Key Embedded Encryption Library. Note that the Asymmetric library also offers the SHA-1, MD5 and the DRBG library functions. • A C header file (or Assembler Include file) that is specified in the description of the function in this guide. The C header file is located in the “include\c” path under the folder where this library is installed. The Assembler Include file is located in the “include\asm” path under the folder where this library is installed. These files provide the function prototypes, #defines and typedefs used by the library. • ret_codes.h file for development in C, or ret_codes.inc file for development in assembly-language These files define various return codes that specify a successful or failed operation. When compiling an application, the C header file must be referenced (using #include) by all source files which call a function in the library or use its symbols or typedefs. When linking an application, “libSymCrypto.a” must be provided as an input to the linker (using the --library or -l linker switch) so that the functions used by the application may be linked into the application.

DS51468B-page 10

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library The linker will place the functions of the library into a special text section named “.libSymCrypto”. This can be seen by looking at the map file generated by the linker.

2.4.2

Memory Models

The dsPIC30F Symmetric Key Embedded Encryption Library functions were developed purely in assembly language and the library was built using the assembler and linker tools in the MPLAB C30 tool suite. The entire library resides within a section named “.libSymCrypto”. RCALL instructions have been used within the library functions to call other library functions. Hence, the library follows a small code model.

2.4.3

Library Function Calling Convention

All the functions within the dsPIC30F Symmetric Key Embedded Encryption Library are compliant with the C compatibility guidelines for the dsPIC30F DSC and follow the function call conventions documented in the “MPLAB C30 C Compiler User’s Guide” (DS51284). Specifically, functions may use the first eight working registers (W0 through W7) as function arguments. Any additional function arguments are passed through the stack. The working registers W0 to W7 are treated as scratch memory, and their values may not be preserved after the function call. On the other hand, if any of the working registers W8 to W13 are used by a function, the working register is first saved, the register is used, and then its original value is restored upon function return. The return value of a (non void) function is available in working register W0 (also referred to as WREG). When needed, the run time software stack is used following the C system stack rules described in the “MPLAB C30 Compiler User’s Guide”. Based on these guidelines, the object modules of the library can be linked to either a C program, an assembly program, or a program which combines code in both languages.

2.4.4

Data Types

The operations performed by the dsPIC30F Symmetric Key Embedded Encryption Library have been designed to take advantage of the DSP instruction set and architectural features of the dsPIC30F DSC. However, as one may expect in an encryption application, none of the computations use floating-point, fractional or signed integer arithmetic. All mathematical operations are perform using unsigned integer arithmetic. To achieve this end, all saturation and rounding modes supported by the accumulators are either disabled or not used. If MAC-class of instructions are used, they are used in unsigned integer mode.

2.4.5

Data Memory Usage

The dsPIC30F Symmetric Key Embedded Encryption Library performs no allocation of RAM, and leaves this task to the user. If the user does not allocate the appropriate amount of memory and align the data properly, undesired results will occur when the function executes. In addition, to minimize execution time, the library may not perform extensive checking on the provided function arguments (including pointers to data memory), to determine if they are valid. Many functions accept data pointers as function arguments, which contain the data to be operated on, and typically also the location to store the result. For convenience, most functions in the library expect their input arguments to be allocated in the default RAM memory space (X-Data or Y-Data), and the output to be stored back into the default RAM memory space. However, the more computational intensive functions require that some operands reside in X-Data and Y-Data, so that the operation can take advantage of the dual data fetch capability of the dsPIC30F architecture.

© 2006 Microchip Technology Inc.

DS51468B-page 11

dsPIC30F Embedded Encryption Libraries User’s Guide 2.4.6

CORCON Register Usage

Many functions of the dsPIC30F Symmetric Key Embedded Encryption Library place the dsPIC30F device into a special operating mode by modifying the CORCON register. On the entry of these functions, the CORCON register is NOT pushed to the stack. It is simply modified to correctly perform the desired operation. Likewise, the CORCON register is not restored to its original value. This mechanism allows the library to execute as correctly and quickly as possible. The application should save CORCON before calling a library function and restore it upon return, if the library function description indicates that CORCON is modified. When the CORCON register is modified, it is typically set such that the dsPIC30F operates in the following mode: • • • •

DSP multiplies are set to unsigned integer data Accumulator saturation is disabled for Accumulator A and Accumulator B Data Space Write Saturation is disabled Program Space Visibility disabled

For a detailed explanation of the CORCON register and its effects, refer to the “dsPIC30F Family Reference Manual” (DS70046).

2.4.7

Integrating with Interrupts and an RTOS

The dsPIC30F Symmetric Key Embedded Encryption Library may easily be integrated into an application which utilizes interrupts or an RTOS, yet certain guidelines must be followed. To minimize execution time, the library utilizes DO loops, REPEAT loops and modulo addressing. Each of these components is a finite hardware resource on the dsPIC30F DSC, and the background code must consider the use of each resource when disrupting execution of a library function. When integrating with the library, you must examine the Function Profile of each function description to determine which resources are used. If a library function will be interrupted, it is your responsibility to save and restore the contents of all registers used by the function, including the state of the DO, REPEAT and special addressing hardware. Naturally this also includes saving and restoring the contents of the CORCON and Status registers.

DS51468B-page 12

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Chapter 3. Symmetric Key Encryption Utilities 3.1

INTRODUCTION This chapter describes the library functions provided in the dsPIC DSC Symmetric Key Embedded Encryption Library, that directly protect application data. These library functions include the Triple-Data Encryption Algorithm (Triple-DES) and Advanced Encryption Standard (AES) encryption primitives and the modes of operation necessary to use them in encrypting, decrypting or authenticating data.

3.2

HIGHLIGHTS This chapter covers the following topics: • • • •

3.3

Encrypting Messages: Modes of Operation and Padding Message Authentication Modes Combined Message Authentication and Encryption Modes Symmetric Key Encryption/Decryption Functions

ENCRYPTING MESSAGES: MODES OF OPERATION AND PADDING This library provides implementations of the TDES and AES block ciphers. These ciphers operate on individual blocks of data – 8 bytes in the case of TDES, 16 bytes in the case of AES. However, in most real-world situations, a block cipher will be used to encrypt a considerably longer message, and one which is not necessarily a multiple of the block size. We define modes of operation to allow us to encrypt variable-length messages. This section describes the modes of operation supported by this library and the considerations to be taken into account when choosing which one to employ.

3.3.1

Electronic Code Book (ECB)

Electronic Code Book (ECB) mode consists of treating the message as a series of input blocks to the underlying block cipher, and encrypting each of them independently. One effect of ECB is that the same plain text will always encrypt to the same ciphertext, and this can lead to leakage of information: for example, if the headers of a message were encrypted with ECB, an observer could tell if two messages were being sent to the same person or to two different people. Additionally, if a block of text repeats in a message, ECB encryption may leak this fact. ECB is therefore only recommended for the encryption of short, highly random messages such as keys. For longer or structured messages, some other mode should be used. Note:

© 2006 Microchip Technology Inc.

In this library, only input that is a multiple of the block size can be submitted for ECB mode encryption or decryption. See the ECB functions (aes_ecb_encrypt, aes_ecb_decrypt, tdes_ecb_encrypt, tdes_ecb_decrypt) for more details.

DS51468B-page 13

dsPIC30F Embedded Encryption Libraries User’s Guide 3.3.2

Cipher Block Chaining (CBC)

Cipher Block Chaining mode allows the plain text to be “randomized” before encryption so that structure in the plain text does not result in structure in the ciphertext. This mode is better suited for the encryption of long messages than ECB. It is used in many standards such as IPsec, SSL (for certain ciphersuites), and S/MIME. This mode is found in the NIST Special Publication 800-38A at http://csrc.nist.gov/publications/nistpubs/. To encrypt in CBC mode, an Initialization Vector (IV) the same length as the block size of the underlying block cipher is selected. Then the plain text P is broken into blocks P1, … , Pn the same size as this block size, and the ciphertext C1, … , Cn is calculated as: Enc ( P1 ⊕ IV ) = C1; Enc ( P2 ⊕ C1 ) = C2; Enc ( P3 ⊕ C2 ) = C3; … Enc ( Pn ⊕ Cn-1 ) = Cn; To decrypt, the same IV must be by the recipient. The ciphertext is split into blocks of the appropriate length C1, … , Cn, and the plain text P1, … , Pn is calculated as: (IV ⊕ Dec ( C1 )) = P1; (C1 ⊕ Dec ( C2 )) = P2; (C2 ⊕ Dec ( C3 )) = P3; … (Cn-1 ⊕ Dec ( Cn )) = Pn; The IV should be different for each message, and may be sent unencrypted. Different standards provide for different methods for agreeing on the IV, and so this library leaves setting the IV to the application developer. 3.3.2.1

CBC MODE AND KEY LIFETIME

Assume the block size of a cipher is b bytes, or B = 8b bits. If one key is used to encrypt more than 2B/2 blocks, there is a high probability that some blocks of ciphertext will repeat, increasing the potential of leaking information about the underlying plain text. Although this condition rarely amounts to a significant attack, it means that the encryption falls short of perfect security. Therefore, a common recommendation is for keys used for CBC mode to be replaced after they have been used to encrypt about 2B/3 blocks, and certainly no more than 2B/2 blocks. This is about 1,000,000-1,000,000,000 blocks for TDES, and 1,000,000,000,000-1,000,000,000,000,000,000 blocks for AES.

DS51468B-page 14

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library 3.3.2.2

CBC MODE AND PADDING

In CBC mode, the encryption mechanism splits the message into blocks the same size as the block size of the underlying block cipher. If the original message is not a multiple of the block size, it must be padded to the appropriate length. The recipient must then unpad the received decrypted message in order to recover the exact message that the sender sent. The sender and the recipient must both use the same padding method in order for the decryption to be successful. This library provides for two means of performing padding and unpadding: • Padding can be performed internally to the aes_cbc_encrypt or tdes_cbc_encrypt function. Unpadding can be performed internally to the aes_cbc_decrypt or tdes_cbc_decrypt function by setting the appropriate flag. Only when the final plain text block is being encrypted can aes_cbc_encrypt and tdes_cbc_encrypt be passed data that is not a multiple of the block size. • The application developer can pad by other means before calling the aes_cbc_encrypt or tdes_cbc_encrypt function, can unpad after calling the aes_cbc_decrypt or tdes_cbc_decrypt function, and can pass these functions only messages that are an exact multiple of the block size in length. If padding is performed automatically, the form of the padding follows the method specified in the PKCS#5, PKCS#7 and S/MIME standards (among others). In this case, the encryption function considers the number of bytes that must be added to the end of the message to make it a multiple of the block size in length. If one byte must be added, it adds one byte with the value 01. If two bytes must be added, it adds the byte string 02 02. If three must be added, it adds the byte string 03 03 03, and so on, and if the message is a multiple of the block size b, it adds an entire block consisting of the value b repeated b times. On decryption, if the appropriate flag is set, the decrypt function attempts to remove the padding, and returns an error if the padding is not of the correct form. To simplify the allocation of output memory, only input that is a multiple of the block size can be submitted for CBC mode encryption or decryption, unless the final plain text block is being encrypted and internal padding is requested. All CBC-encrypted messages will be a multiple of the block size in length, so all inputs must be a multiple of the block size on decryption. Note:

© 2006 Microchip Technology Inc.

If the internal padding is being performed and the input plain text is a multiple of the block size, the output ciphertext will be one block longer than the input plain text. The ciphertext buffer must be long enough to receive this ciphertext.

DS51468B-page 15

dsPIC30F Embedded Encryption Libraries User’s Guide 3.3.2.3

CBC MODE AND AUTHENTICATION

CBC Mode only provides confidentiality. The mere fact that a padded message, encrypted with CBC, has decrypted and unpadded correctly should not be taken as evidence that the message has not been altered by an attacker. For full security, we recommend that CBC only be used in conjunction with some message authentication mechanism, such as the CBC-MAC mechanism provided for symmetric authentication in this library and described below. Note:

If a message is encrypted with CBC mode and authenticated with CBC-MAC, the encryption and authentication MUST use different keys.

The default method of accomplishing both encryption and authentication provided by this library, is to encrypt and authenticate using the combined mode CCM, described below. We recommend that CCM be used by default for application development unless there are interoperability reasons to consider some other mode.

3.3.3

Counter Mode (CTR)

Counter mode is a parallelizable alternative to CBC mode, which also uses an Initialization Vector (IV). In this mode, the IV must be different for each encrypted message. This mode is found in the NIST Special Publication 800-38A at http://csrc.nist.gov/publications/nistpubs. Even if the same plain text is encrypted on two separate occasions, the varying Initialization Vector ensures that an attacker will not be able to detect the repeated plain text. To encrypt in CTR mode, an Initialization Vector the same length as the block size of the underlying block cipher is selected. Then the plain text P is broken into blocks P1, … , Pn the same size as this block size, and the ciphertext C1, … , Cn is calculated as: P1 ⊕ Enc ( IV ) = C1; P2 ⊕ Enc ( IV+1 ) = C2; P3 ⊕ Enc ( IV+2 ) = C3; … Pn ⊕ Enc ( IV+n-1 ) = Cn; The sender treats the Initialization Vector as an integer and increments it by one before encrypting each block. To decrypt, the recipient must use the same Initialization Vector, split the ciphertext into blocks of the appropriate length C1, … , Cn, and then calculate the plain text P1, … , Pn as: C1 ⊕ Enc ( IV ) = P1; C2 ⊕ Enc ( IV+1 ) = P2; C3 ⊕ Enc ( IV+2 ) = P3; … Cn ⊕ Enc ( IV+n-1 ) = Pn; The Initialization Vector should be different for each message. It can be sent unencrypted. See below for further considerations on choice of IV. Different standards provide for different methods for agreeing on the Initialization Vector, so this library does not enforce a specific means for setting it.

DS51468B-page 16

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library In CTR mode, messages do not have to be a multiple of the block size in length; if Pn is less than a full block, the sender simply truncates Enc(IV+n-1) to the appropriate length before XORing, and the recipient does the same on decryption. Therefore, issues concerning padding do not arise in CTR mode. Incrementing the counter and processing input less than a full block are handled internally by the library functions. The encryption and decryption functions for Counter Mode are the same. The toolkit therefore does not include a separate decryption function for Counter Mode. 3.3.3.1

CTR MODE, KEY LIFETIME AND CHOICE OF INITIALIZATION VECTOR

If the same Initialization Vector value is used twice for CTR mode encryption with the same key, the security of both encrypted messages is compromised. It is vital that Initialization Vector values never repeat in CTR mode, including any value from IV to IV+n-1 that has been used at any stage. One method for achieving this is to initialize the IV at 000….000 when the key is first agreed upon, to store the last encrypted IV value for each message, and to increment this value by 1 at the start of encrypting the next message. There are other, more sophisticated methods used in other standards, such as the IV generation method used within CCM mode, also provided in this library. If the IV does not repeat, the recommended key lifetime is calculated as follows. Say the block size of a cipher is b bytes, or B = 8b bits. If one key is used to encrypt more than 2B/2 blocks, there is a high probability that some blocks of ciphertext will repeat, increasing the potential of leaking some information about the underlying plain text. Although this will rarely amount to a significant attack, it means that the encryption falls short of perfect security. Therefore, a common recommendation is that keys used for CTR mode should be replaced once they have been used to encrypt about 2B/3 blocks, and certainly no more than 2B/2 blocks. This is about 1,000,000-1,000,000,000 blocks for TDES, and 1,000,000,000,000- 1,000,000,000,000,000,000 blocks for AES. 3.3.3.2

CTR MODE AND AUTHENTICATION

CTR mode can be considered a stream cipher based on a block cipher. If messages encrypted with CTR mode are not authenticated, an attacker can alter them at will: XORing any value with the ciphertext will result in the same value being altered with the plain text on decryption. CTR mode must therefore only be used in conjunction with a cryptographically secure authentication mechanism, such as the CBC-MAC mechanism provided for symmetric authentication in this library and described below. One means of accomplishing this, provided by this library, is to encrypt and authenticate using the combined mode CCM, described below. We recommend that CCM be used by default for application development unless there are interoperability reasons to consider some other mode.

© 2006 Microchip Technology Inc.

DS51468B-page 17

dsPIC30F Embedded Encryption Libraries User’s Guide 3.4

MESSAGE AUTHENTICATION MODES The recipient of a message frequently wants to know that the message (a) came from the correct source and (b) has not been altered since that source sent it. One means of providing this assurance, possible if the sender and recipient share a symmetric key, is to perform symmetric message authentication. This is a two-stage process. On sending, the sender uses the key to generate a message authentication code (MAC) based on the message. This MAC is linked to the message and the key so that only the keyholders can generate the MAC, and changing any part of the message results in the MAC being changed unpredictably. The sender sends both the message itself and the MAC to the recipient. On receipt of the message and MAC, the recipient also uses the key to generate a MAC based on the message. He compares the generated MAC to the received MAC. If the two MACs are the same, he knows that the received MAC was generated by the sender, and that the message has not been altered in transit. We therefore say he has authenticated the message. A symmetric message authentication method is secure if an attacker cannot produce a MAC on a fresh message. In other words, say an attacker has already seen the MACs on messages m1, … , mn-1. If the attacker can produce a message mn, not included in the list of messages he has already seen, and the corresponding MAC without knowing the symmetric key, then the authentication method is not secure. If an attacker cannot produce a MAC on any message he has not seen, the authentication method is secure. This library provides two means for symmetric message authentication: • The FIPS-113 CBC-MAC, using both TDES and AES. • The CCM mode of operation, using AES.

3.4.1

FIPS-113 CBC-MAC

The FIPS-113 CBC-MAC is a standards-based symmetric message authentication method, defined in NIST FIPS PUB 113, available from http://www.itl.nist.gov/fipspubs/fip113.htm. The CCM mode of operation is included in many emerging standards, including IEEE 802.11i. 3.4.1.1

FIPS-113 CBC-MAC AND VARIABLE LENGTH MESSAGES

The CBC-MAC as specified in the FIPS-113 standard and provided in this library is only secure if all messages authenticated with the same key are of the same length. For example, a custom protocol might require all packets to be 64 bytes long. In this case, the FIPS-113 CBC-MAC would be appropriate to use. However, if the protocol allowed packets of length 64, 72, or 80 bytes, then it would not be secure to use the FIPS-113 CBC-MAC. The FIPS-113 CBC-MAC allows for the size of the input to be other than a multiple of the block size. When this condition occurs, the CBC-MAC functions, aes_cbc_mac and tdes_cbc_mac automatically pad the last input block with zeros before completing the calculation. If one key may authenticate messages of variable length, the recommended symmetric authentication method in this library is CCM, described later. Note that this library does not support securely authenticating variable-length messages with a TDES-based mechanism.

DS51468B-page 18

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library 3.4.2

Symmetric Authentication Methods and Key Lifetime

Say the block size of a cipher is b bytes, or B = 8b bits. Then, if one key is used to encrypt more than 2B/2 messages, with high probability some MACs will repeat, allowing an attacker to forge MACs on unseen messages. Therefore, a common recommendation is that keys used for CBC-MAC or CCM should be replaced once they have been used to encrypt about 2B/3 blocks, and certainly no more than 2B/2 blocks. This is about 1,000,000-1,000,000,000 blocks for TDES, and 1,000,000,000,0001,000,000,000,000,000,000 blocks for AES.

3.5

COMBINED MESSAGE AUTHENTICATION AND ENCRYPTION MODES CBC-MAC can be used to provide encryption and authentication in combination with any of the modes of operation for encryption described earlier. Note:

3.5.1

If a message is encrypted with CBC mode, and authenticated with CBC-MAC, the encryption and authentication MUST use different keys.

Combined Encryption and Authentication with CCM

The default method of accomplishing both encryption and authentication provided by this library, is to encrypt and authenticate using the combined Counter and CBC-MAC mode (CCM). We recommend that CCM be used by default for application development unless there are interoperability reasons to consider some other mode. The CCM mode is a recently proposed mode of operation which provides both encryption and authentication, found in the NIST draft Special Publication 800-38C at: http://csrc.nist.gov/publications/drafts/Draft_SP_800-38C_9-04-2003.pdf. It is defined for use with AES, but not with TDES. Each block of the message is processed twice – once for encryption, once for authentication. Note that CCM may be used for authentication only, for encryption and authentication, or for authentication of a message that is partially encrypted and partially sent as plain text. In other words, CCM allows the sender to send an encrypted, authenticated message; or an encrypted, authenticated message with associated plain text header information which is also authenticated; or an authenticated message which is entirely plain text. The authentication with CCM is performed using a CBC-MAC construction. In order to make this authentication secure, the CCM session must be told both the length of the unencrypted header information and the length of the authenticated message. This information must be passed to the CCM session before any actual message data is processed. This makes the API for CCM necessarily slightly more complicated than for the other modes of operation, which give only encryption or only authentication. 3.5.1.1

CCM MODE, KEY LIFETIME, AND CHOICE OF IV

The same security considerations apply to the choice of IV in CCM as in CTR mode: if the same IV value is used twice for CTR mode encryption with the same key, the security of both encrypted messages is compromised. It is vital that IV values never repeat in CTR mode, and this includes any value from IV to IV+n-1 that has been used at any stage. Given that the IV does not repeat, a common recommendation is that keys used for CCM mode should be replaced once they have been used to encrypt about 2B/3 blocks, and certainly no more than 2B/2 blocks. This is about 1,000,000,000,0001,000,000,000,000,000,000 blocks for AES. The reasons for this are explained in the sections on CTR and CBC-MAC, the underlying building blocks for this mode.

© 2006 Microchip Technology Inc.

DS51468B-page 19

dsPIC30F Embedded Encryption Libraries User’s Guide 3.6

SYMMETRIC KEY ENCRYPTION/DECRYPTION FUNCTIONS This section describes individual symmetric key encryption and decryption functions.

3.6.1

Advanced Encryption Standard (AES)

The AES functions described in this section include: • • • • • • • •

aes_encrypt_key_sched aes_decrypt_key_sched aes_ecb_encrypt aes_ecb_decrypt aes_cbc_mac aes_cbc_encrypt aes_cbc_decrypt aes_ctr_crypt

Examples of these functions are provided in Appendix A. “Symmetric Function Examples”. The AES CCM functions are described in Section 3.6.1.1 “Combined CBC-Mac and Counter Mode (CCM) Functions”.

aes_encrypt_key_sched Function:

Computes individual round keys for encryption from an AES key.

C Include:

aes_encrypt.h

ASM Include:

aes_encrypt.inc

Prototype:

extern unsigned short aes_encrypt_key_sched( unsigned long int *enc_round_keys, const unsigned char *key);

Arguments:

enc_round_keys A pointer to a buffer consisting of 44 32-bit words to hold the encryption round keys. key A pointer to the 128-bit encryption key.

DS51468B-page 20

Remarks:

AES uses 11 128-bit subkeys to perform encryption. These subkeys are derived from a single 128-bit symmetric key. This function must be called to derive the subkeys from the symmetric key before any encryption functions can be called. Once the subkeys are computed, they can be used in multiple calls to encryption functions.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS

File Name:

aes_encrypt.s

Files Needed:

aes_encrypt.o

Clock Cycles:

549

Code Example:

aes_encrypt_key_sched(enc_round_keys, key);

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_decrypt_key_sched Function:

Computes individual round keys for decryption from the encryption round keys.

C Include:

aes_decrypt.h

ASM Include:

aes_decrypt.inc

Prototype:

extern unsigned short aes_decrypt_key_sched( unsigned long int *dec_round_keys, const unsigned long int *enc_round_keys);

Arguments:

dec_round_keys A pointer to a buffer consisting of 44 32-bit words to hold the decryption round keys. enc_round_keys A pointer to a buffer that holds the encryption round keys.

Remarks:

AES uses 11 128-bit subkeys to perform decryption. These subkeys are derived from 11 128-bit encryption subkeys. This function must be called to derive the decryption subkeys from the encryption subkeys before any decryption functions can be called. Once the subkeys are computed, they may be used in multiple calls to decryption functions.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS

File Name:

aes_decrypt.s

Files Needed:

aes_decrypt.o

Clock Cycles:

2047

Code Example:

aes_decrypt_key_sched(dec_round_keys, enc_round_keys);

aes_ecb_encrypt Function:

Performs AES encryption in Electronic Code Book mode.

C Include:

aes_ecb.h

ASM Include:

aes_ecb.inc

Prototype:

extern unsigned short aes_ecb_encrypt( unsigned char *out, const unsigned char *in, unsigned short in_byte_len, const unsigned long int *enc_round_keys);

Arguments:

out A pointer to output block storage that must be at least in_byte_len bytes in length. in A pointer to input block storage in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 16 and 65520 inclusive. Must be a multiple of 16. enc_round_keys A pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function.

© 2006 Microchip Technology Inc.

DS51468B-page 21

dsPIC30F Embedded Encryption Libraries User’s Guide aes_ecb_encrypt (Continued) Remarks:

Electronic Code Book mode is the simplest mode of operation for AES. It encrypts each block of plain text independently. The in and out pointers may refer to the same location. An error code of MCL_ILLEGAL_SIZE is returned if in_byte_len is zero, or not a multiple of 16.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

aes_ecb.s

Files Needed:

aes_ecb.o, aes_encrypt.o, aes_decrypt.o

Clock Cycles:

(2039 * no. of blocks) + 58

Code Example:

aes_ecb_encrypt(out, in, in_byte_len, enc_round_keys);

aes_ecb_decrypt Function:

Performs AES decryption in Electronic Code Book mode.

C Include:

aes_ecb.h

ASM Include:

aes_ecb.inc

Prototype:

extern unsigned short aes_ecb_decrypt( unsigned char *out, const unsigned char *in, unsigned short in_byte_len, const unsigned long int *dec_round_keys);

Arguments:

out A pointer to output block storage that must be at least in_byte_len bytes in length. in A pointer to input block storage in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 16 and 65520 inclusive. Must be a multiple of 16. dec_round_keys A pointer to decryption round keys generated by a call to the aes_decrypt_key_sched function.

DS51468B-page 22

Remarks:

Electronic Code Book mode is the simplest mode of operation for AES. It decrypts each block of plain text independently. The in and out pointers may refer to the same location. An error code of MCL_ILLEGAL_SIZE is returned if in_byte_len is zero, or not a multiple of 16.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

aes_ecb.s

Files Needed:

aes_encrypt.o, aes_decrypt.o, aes_ecb.o

Clock Cycles:

(2103 * no. of blocks) + 60

Code Example:

aes_ecb_decrypt(out, in, in_byte_len, dec_round_keys);

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_cbc_mac Function:

Calculates the CBC-MAC authentication code using AES.

C Include:

aes_cbc_encrypt_and_mac.h

ASM Include:

aes_cbc_encrypt_and_mac.inc

Prototype:

extern unsigned short aes_cbc_mac( unsigned char *state, unsigned char *out, const unsigned char *in, unsigned short int in_byte_len, const unsigned long int *enc_round_keys, unsigned short int flags);

Arguments:

state A pointer to a 34-byte buffer of temporary storage space. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[34]; out A pointer to output storage that must be at least 16 bytes in length. This buffer is only used by the function if the AES_FINISH flag is set. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. enc_round_keys A pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function. flags The value of flags can be any combination of the following values (defined in aes.h): AES_INIT Initialize state AES_DATA_ONLY Add input data AES_FINISH Finish computation

Remarks:

Computes the CBC-MAC authentication code as defined in FIPS 113. This function may be called one or more times in the computation of a single MAC value. Calling with the AES_INIT flag resets the initial state. This must be performed at the beginning of the computation of any new MAC value. Calling with the AES_DATA_ONLY flag processes additional data. This may be called zero or more times until all input data has been processed. Calling with AES_FINISH completes processing the input data, finalizes the hash value and stores the result in the buffer out. If AES_FINISH is set, and no data has been processed (in other words, in_byte_len has been zero on all calls since the one with AES_INIT set), the function returns MCL_ILLEGAL_SIZE.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

aes_cbc_encrypt_and_mac.s

Files Needed:

aes_encrypt.o, aes_cbc_encrypt_and_mac.o

Clock Cycles:

(2035 * no. of blocks) + 180

Code Example:

aes_cbc_mac(state, out, in, in_byte_len, enc_round_keys, AES_INIT);

© 2006 Microchip Technology Inc.

DS51468B-page 23

dsPIC30F Embedded Encryption Libraries User’s Guide aes_cbc_encrypt Function:

Encrypts using CBC mode, optionally applying PKCS #5 padding to the final block.

C Include:

aes_cbc_encrypt_and_mac.h

ASM Include:

aes_cbc_encrypt_and_mac.inc

Prototype:

extern unsigned short aes_cbc_encrypt( unsigned char *state, unsigned char *out, unsigned short int *out_byte_len, const unsigned char *in, unsigned short int in_byte_len, const unsigned long int *enc_round_keys, unsigned short int flags);

Arguments:

state A pointer to a 34-byte buffer of temporary storage space. If the AES_INIT flag is set, the first 16 bytes of the buffer must contain the Initialization Vector. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[34]; out A pointer to output storage. See below for length considerations. out_byte_len On success, this will point to the number of output bytes returned. Apart from one exception noted below, this will be in_byte_len The exception occurs in processing the last block of plain text. Padding added by this function through the use of the AES_INTERNAL_PAD flag will increase the length of the output. If AES_FINISH and AES_INTERNAL_PAD are both set, the length of the output will be in_byte_len plus 16 if in_byte_len is divisible by 16. Otherwise, the length will be in_byte_len rounded up so that out_byte_len is divisible by 16. in A pointer to input storage in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. This must be divisible by 16 unless AES_FINISH and AES_INTERNAL_PAD are both set. enc_round_keys A pointer to decryption round keys generated by a call to the aes_encrypt_key_sched function. flags The value of flags can be any combination of the following values (defined in aes.h): AES_INIT Initialize state AES_DATA_ONLY Add input data AES_FINISH Finish computation AES_INTERNAL_PAD Apply padding internally

Remarks:

DS51468B-page 24

The in and out pointers may refer to the same memory location, so long as there is enough memory allocated at this location to hold the output data. If AES_FINISH is set, and no data has been processed (in other words, in_byte_len has been zero on all calls since the one with AES_INIT set), the function returns MCL_ILLEGAL_SIZE. It also returns MCL_ILLEGAL_SIZE if in_byte_len is not a multiple of 16 and either AES_FINISH or AES_INTERNAL_PAD is not set.

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_cbc_encrypt (Continued) Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

aes_cbc_encrypt_and_mac.s

Files Needed:

aes_encrypt.o, aes_cbc_encrypt_and_mac.o

Clock Cycles:

(2059 * no. of blocks) + 172 (no internal padding) (2059 * no. of blocks) + 2233 (with internal padding (if it adds a block))

Code Example:

aes_cbc_encrypt(state, out, out_byte_len, in, in_byte_len, enc_round_keys, AES_INIT);

aes_cbc_decrypt Function:

Decrypt using CBC mode, optionally removing PKCS #5 padding from the final block.

C Include:

aes_cbc_decrypt.h

ASM Include:

aes_cbc_decrypt.inc

Prototype:

extern unsigned short aes_cbc_decrypt( unsigned char *state, unsigned char *out, unsigned short int *out_byte_len, const unsigned char *in, unsigned short int in_byte_len, const unsigned long int *dec_round_keys, unsigned short int flags);

Arguments:

state A pointer to a 32-byte buffer of temporary storage space. If the AES_INIT flag is set, the first 16 bytes of the buffer must contain the Initialization Vector. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[32]; out A pointer to output storage. See below for length considerations. out_byte_len On success, this will point to the number of output bytes returned. Apart from one exception noted below, this will be in_byte_len. The exception occurs in processing the last block of ciphertext. Padding stripped by this function through the use of the AES_INTERNAL_PAD flag will decrease the length of the output. If AES_FINISH and AES_INTERNAL_PAD are both set, the length of the output will be in the range in_byte_len minus 16 to in_byte_len minus 1. in A pointer to input storage in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65520 inclusive. Must be a multiple of 16 and must be non-zero when AES_FINISH is set. dec_round_keys A pointer to decryption round keys generated by a call to the aes_decrypt_key_sched function.

© 2006 Microchip Technology Inc.

DS51468B-page 25

dsPIC30F Embedded Encryption Libraries User’s Guide aes_cbc_decrypt (Continued) flags The value of flags can be any combination of the following values (defined in aes.h): AES_INIT Initialize state AES_DATA_ONLY Add input data AES_FINISH Finish computation AES_INTERNAL_PAD Strip internal padding Remarks:

The in and out pointers may refer to the same memory location. • An error code of MCL_ILLEGAL_SIZE is returned if in_byte_len is not a multiple of 16, or in_byte_len = 0 when the AES_FINISH flag is set. • An error code of MCL_ILLEGAL_PADDING is returned if the padding was incorrect.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE MCL_ILLEGAL_PADDING

File Name:

aes_cbc_encrypt_and_mac.s

Files Needed:

aes_decrypt.o, aes_cbc_decrypt.o

Clock Cycles:

(2135 * no. of blocks) + 162 (note that if internal padding was used, there could be an extra block)

Code Example:

aes_cbc_decrypt(state, out, out_byte_len, in, in_byte_len, dec_round_keys, AES_INIT);

aes_ctr_crypt Function:

Encrypts or decrypts using CTR mode.

C Include:

aes_ctr.h

ASM Include:

aes_ctr.inc

Prototype:

extern unsigned short aes_ctr_crypt( unsigned char *state, unsigned char *out, const unsigned char *in, unsigned short int in_byte_len, const unsigned long int *enc_round_keys, unsigned short int flags);

Arguments:

state A pointer to a 34-byte buffer of temporary storage space. If the AES_INIT flag is set, the first 16 bytes of the buffer must contain the Initialization Vector. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[34]; out A pointer to output storage that is in_byte_len bytes in length. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. enc_round_keys A pointer to round keys generated by a call to the aes_encrypt_key_sched function.

DS51468B-page 26

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_ctr_crypt (Continued) flags The value of flags can be any combination of the following values (defined in aes.h): AES_INIT Initialize state AES_DATA_ONLY Add input data AES_FINISH Finish computation Remarks:

The in and out pointers may refer to the same memory location. This function is used to perform both encryption and decryption. If AES_FINISH is set, and no data has been processed (in other words, in_byte_len has been zero on all calls since the one with AES_INIT set), the function returns MCL_ILLEGAL_SIZE.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

aes_ctr.s

Files Needed:

aes_encrypt.o, aes_ctr.o

Clock Cycles:

(2124 * no. of blocks) + 108

Code Example:

aes_ctr_crypt(state, out, in, in_byte_len, enc_round_keys, AES_INIT);

© 2006 Microchip Technology Inc.

DS51468B-page 27

dsPIC30F Embedded Encryption Libraries User’s Guide 3.6.1.1

COMBINED CBC-MAC AND COUNTER MODE (CCM) FUNCTIONS

CCM mode of AES is a combination of CBC-MAC and Counter Mode. These functions enable you to both encrypt and authenticate data. All data is authenticated. Some data may be both authenticated and encrypted. AES CCM mode functions include: • • • • • •

aes_ccm_init_encryption_and_mac aes_ccm_init_decryption_and_verification aes_ccm_input_AD aes_ccm_crypt_AED aes_ccm_get_mac aes_ccm_verify_mac

Examples of these functions are described in Appendix A. “Symmetric Function Examples”. 3.6.1.1.1

How to Authenticate and Optionally Encrypt

The following steps should be performed when authenticating and optionally encrypting data: 1. When authenticating or authenticating-and-encrypting data, we first call aes_ccm_init_encryption_and_mac to prepare the state buffer for use by subsequent functions. This function must be told the length of the unencrypted and the encrypted data in advance: it uses this information to prepare internal state information. 2. The data is then processed to authenticate but not encrypt (the Associated or Authenticated Data, or AD) using the aes_ccm_input_AD function. If there is no AD, i.e., if all data is being both authenticated and encrypted, then this function is not called. 3. Next, the data is processed to both authenticate and encrypt (the Authenticated and Encrypted Data, or AED) using the aes_ccm_crypt_AED function. If there is no AED, i.e., if all data is being authenticated only, then this function is not called. 4. When all data has been processed the encrypted MAC on the entire message is obtained by calling aes_ccm_get_mac. The authenticated and optionally encrypted data then consists of: • Authenticated but not encrypted data • Ciphertext output by aes_ccm_crypt_AED • Encrypted authentication value output by aes_ccm_get_mac All three must be kept for successful verification and optional decryption. Note that when encrypting and/or authenticating a message, the aes_ccm_input_AD and aes_ccm_crypt_AED functions do not check that the AD and AED are of the lengths specified in the call to aes_ccm_init_encryption_and_mac. It is up to the developer to ensure that the input data is consistent. 3.6.1.1.2

How to Verify and Decrypt

As with encryption and/or authentication, you call functions aes_ccm_init_decryption_and_verification, aes_ccm_input_AD and aes_ccm_crypt_AED as many times as needed to decrypt and/or verify data. The data output by aes_ccm_crypt_AED is now the plain text. However it is very important that this plain text not be acted on. For example, the plain text should not be displayed to a user until it has been verified as tamper-free. Verification is done by the function aes_ccm_verify_mac(), which indicates success or failure.

DS51468B-page 28

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_ccm_init_encryption_and_mac Function:

Prepares state for input data encryption and MAC generation using CCM mode.

C Include:

aes_ccm.h

ASM Include:

aes_ccm.inc

Prototype:

extern unsigned short aes_ccm_init_encryption_and_mac( unsigned char *state, const unsigned char *AD_byte_len, unsigned short int ADlen_byte_len, const unsigned char *AED_byte_len, unsigned short int AEDlen_byte_len, const unsigned char *nonce, unsigned short int nonce_byte_len, unsigned short int MAC_byte_len, const unsigned long int *enc_round_keys);

Arguments:

state A pointer to a 92-byte buffer of temporary storage space. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[92]; AD_byte_len A pointer to a buffer containing the length in bytes of the AD (Authenticated Data), represented as a big-endian integer up to 8 bytes in length. ADlen_byte_len The length of the length data contained in AD_byte_len. Must be between 0 and 8 inclusive. AED_byte_len A pointer to a buffer containing the length in bytes of the AED (Authenticated and Encrypted Data), represented as a big-endian integer 2-8 bytes in length. AEDlen_byte_len The length of the length data contained in AED_byte_len. Must be between 2 and 8 inclusive. nonce A pointer to the nonce. nonce_byte_len The length in bytes of the nonce, equal to 15 - AEDlen_byte_len. MAC_byte_len The length in bytes of the final MAC value which is output at the end of the encryption and authentication process. Must take the value 4, 6, 8, 10, 12, 14 or 16. enc_round_keys A pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function.

© 2006 Microchip Technology Inc.

DS51468B-page 29

dsPIC30F Embedded Encryption Libraries User’s Guide aes_ccm_init_encryption_and_mac (Continued) Remarks:

The encoded lengths in AD_byte_len and AED_byte_len may have leading zeroes. For example, setting the contents of AD_byte_len to ‘03’ and setting ADlen_byte_len to ‘1’ has the same effect as setting the contents of AD_byte_len to ‘00 03’ and setting ADlen_byte_len to ‘2’. An error code of MCL_ILLEGAL_PARAMETER is returned if any of the following situations occur: MAC_byte_len differs from 4, 6, 8, 10, 12, 14 or 16, AEDlen_byte_len is less than 2 or over 8, or the sum AEDlen_byte_len + nonce_byte_len differs from 15.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_PARAMETER

File Name:

aes_ccm.s

Files Needed:

aes_ccm.o, aes_encrypt.o, aes_cbc_encrypt_and_mac.o, aes_ctr.o

Clock Cycles:

2457 typical

Code Example:

aes_ccm_init_encryption_and_mac(state, AD_byte_len, ADlen_byte_len, AED_byte_len, AEDlen_byte_len, nonce, nonce_byte_len, MAC_byte_len, enc_round_keys);

aes_ccm_init_decryption_and_verification Function:

Prepares state for input data decryption and MAC verification using CCM mode.

C Include:

aes_ccm.h

ASM Include:

aes_ccm.inc

Prototype:

extern unsigned short aes_ccm_init_decryption_and_verification( unsigned char *state, const unsigned char *AD_byte_len, unsigned short int ADlen_byte_len, const unsigned char *AED_byte_len, unsigned short int AEDlen_byte_len, const unsigned char *nonce, unsigned short int nonce_byte_len, unsigned short int MAC_byte_len, const unsigned long int *enc_round_keys);

Arguments:

state A pointer to a 92-byte buffer of temporary storage space. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[92]; AD_byte_len A pointer to a buffer containing the length in bytes of the AD (Authenticated Data), represented as a big-endian integer up to 8 bytes in length. ADlen_byte_len The length of the length data contained in AD_byte_len. Must be 0-8 inclusive.

DS51468B-page 30

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_ccm_init_decryption_and_verification (Continued) AED_byte_len A pointer to a buffer containing the length in bytes of the AED (Authenticated and Encrypted Data), represented as a big-endian integer 2-8 bytes in length. AEDlen_byte_len The length of the length data contained in AED_byte_len. Must be 2-8 inclusive. nonce A pointer to the nonce. nonce_byte_len The length in bytes of the nonce, equal to 15 - AEDlen_byte_len. MAC_byte_len The length in bytes of the final MAC value which is output at the end of the encryption and authentication process. Must take the value 4, 6, 8, 10, 12, 14 or 16. enc_round_keys A pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function. Remarks:

The encoded lengths in AD_byte_len and AED_byte_len may have leading zeroes. For example, setting the contents of AD_byte_len to ‘03’ and setting ADlen_byte_len to ‘1’ has the same effect as setting the contents of AD_byte_len to ‘00 03’ and setting ADlen_byte_len to 2. The nonce, AD_byte_len and AED_byte_len, and their associated lengths, must be obtained by out-of-band means. Encryption and decryption both use the encryption round keys generated by a call to the aes_encrypt_key_sched function. An error code of MCL_ILLEGAL_PARAMETER is returned if any of the following situations occur: MAC_byte_len differs from 4, 6, 8, 10, 12, 14 or 16, AEDlen_byte_len is less than 2 or over 8, or the sum AEDlen_byte_len + nonce_byte_len differs from 15.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_PARAMETER

File Name:

aes_ccm.s

Files Needed:

aes_ccm.o, aes_encrypt.o, aes_cbc_encrypt_and_mac.o, aes_ctr.o

Clock Cycles:

2458 typical

Code Example:

aes_ccm_init_decryption_and_verification(state, AD_byte_len, ADlen_byte_len, AED_byte_len, AEDlen_byte_len, nonce, nonce_byte_len, MAC_byte_len, enc_round_keys);

© 2006 Microchip Technology Inc.

DS51468B-page 31

dsPIC30F Embedded Encryption Libraries User’s Guide aes_ccm_input_AD Function:

Processes data which will be MACed (if the sender calls this function) or verified (if the receiver called it), but not encrypted or decrypted.

C Include:

aes_ccm.h

ASM Include:

aes_ccm.inc

Prototype:

extern unsigned short aes_ccm_input_AD( unsigned char *state, unsigned short int *out_byte_len, const unsigned char *in, unsigned short int in_byte_len, const unsigned long int *enc_round_keys);

Arguments:

state A pointer to a 92-byte buffer of temporary storage space, which has previously been initialized by calling: aes_ccm_init_encryption_and_mac or aes_ccm_init_decryption_and_verification. out_byte_len A pointer to the number of output bytes returned ranging between 0 and 65535 inclusive. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. enc_round_keys A pointer to round keys generated by a call to the aes_encrypt_key_sched function.

DS51468B-page 32

Remarks:

The output of CCM encryption and authentication consists of the concatenation of the AD, the AED and the MAC value. When processing the AD part of a received message, the library keeps track of the number of bytes processed to date. If the input data consists of the end of the AD followed by the start of the (encrypted) AED, the aes_ccm_input_AD function processes only the AD. In this case, the function returns MCL_SUCCESS, and out_byte_len contains the number of bytes of AD processed. This is the only case in which out_byte_len differs from in_byte_len. The trailing (in_byte_len - out_byte_len) bytes of in should then be passed to aes_ccm_crypt_AED. When this function is used to generate authentication data, it does not check that the total input length of the AD corresponds to the value passed as AD_byte_len to aes_ccm_init_encryption_and_MAC. When the message is being sent, it is up to the developer to ensure that the input data is consistent.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS

File Name:

aes_ccm.s

Files Needed:

aes_encrypt.o, aes_ccm.o, aes_cbc_encrypt_and_mac.o

Clock Cycles:

(2035 * no. of blocks) + 160

Code Example:

aes_ccm_input_AD(state, out_byte_len, in, in_byte_len, enc_round_keys);

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_ccm_crypt_AED Function:

Encrypt or decrypt data in CCM mode, also inputting the data to the ongoing authentication process.

C Include:

aes_ccm.h

ASM Include:

aes_ccm.inc

Prototype:

extern unsigned short aes_ccm_crypt_AED( unsigned char *state, unsigned char *out, unsigned short int *out_byte_len, const unsigned char *in, unsigned short int in_byte_len, const unsigned long int *enc_round_keys);

Arguments:

state A pointer to a 92-byte buffer of temporary storage space, which has previously been initialized by calling: aes_ccm_init_encryption_and_mac or aes_ccm_init_decryption_and_verification, and may subsequently have been passed to aes_ccm_input_AD. out A pointer to output storage that is in_byte_len bytes in length. out_byte_len A pointer to the number of output bytes returned ranging between 0 and 65535 inclusive. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. enc_round_keys A pointer to round keys generated by a call to the aes_encrypt_key_sched function.

Remarks:

© 2006 Microchip Technology Inc.

The in and out pointers may refer to the same memory location. The output of CCM encryption and authentication consists of the concatenation of the AD, the AED, and the MAC value. When processing the AED part of a received message, the library keeps track of the number of bytes processed to date. If the input data consists of the end of the AED followed by the start of the MAC, the aes_ccm_crypt_AED function processes only the AED. In this case, the function returns MCL_SUCCESS, and out_byte_len contain the number of bytes of AED processed. This is the only case in which out_byte_len differs from in_byte_len. The trailing (in_byte_len - out_byte_len) bytes of in should then be passed to aes_ccm_verify_mac. When this function is used to generate authentication data, it does not check that the total input length of the AED corresponds to the value passed as AED_byte_len to aes_ccm_init_encryption_and_MAC. When the message is being sent, it is up to the developer to ensure that the input data is consistent.

DS51468B-page 33

dsPIC30F Embedded Encryption Libraries User’s Guide aes_ccm_crypt_AED (Continued) Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS

File Name:

aes_ccm.s

Files Needed:

aes_encrypt.o, aes_ccm.o, aes_cbc_encrypt_and_mac.o, aes_ctr.o

Clock Cycles:

(4159 * no. of blocks) + 223

Code Example:

aes_ccm_crypt_AED(state, out, in, in_byte_len, enc_round_keys);

aes_ccm_get_mac Function:

Outputs the encrypted MAC for a CCM-processed message.

C Include:

aes_ccm.h

ASM Include:

aes_ccm.inc

Prototype:

extern unsigned short aes_ccm_get_mac( unsigned char *state, unsigned char *mac, const unsigned long int *enc_round_keys);

Arguments:

state A pointer to a 92-byte buffer of temporary storage space, which has previously been initialized by calling: aes_ccm_init_encryption_and_mac, and may subsequently have been passed to aes_ccm_input_AD and aes_ccm_crypt_AED. mac A pointer to output storage whose length in bytes was given in the MAC_byte_len argument passed to aes_ccm_init_encryption_and_verify. enc_round_keys A pointer to round keys generated by a call to the aes_encrypt_key_sched function.

DS51468B-page 34

Remarks:

The IV (initial counter) must be supplied in the beginning of the state buffer when the AES_INIT flag is set. This routine uses 2 levels of (nested) DO loops.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS

File Name:

aes_ccm.s

Files Needed:

aes_encrypt.o, aes_ccm.o, aes_cbc_encrypt_and_mac.o, aes_ctr.o

Clock Cycles:

2440 - 4471

Code Example:

aes_ccm_get_mac(state, mac, enc_round_keys);

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library aes_ccm_verify_mac Function:

Verifies the MAC associated with a CCM data stream.

C Include:

aes_ccm.h

ASM Include:

aes_ccm.inc

Prototype:

extern unsigned short aes_ccm_verify_mac( unsigned char *state, const unsigned char *mac, const unsigned long int *enc_round_keys);

Arguments:

state A pointer to a 92-byte buffer of temporary storage space, which has previously been initialized by calling: aes_ccm_init_decryption_and_verification, and may subsequently have been passed to aes_ccm_input_AD and aes_ccm_crypt_AED. mac A pointer to a buffer containing the encrypted MAC from the end of the CCM-processed message, whose length in bytes was given in the MAC_byte_len argument passed to aes_ccm_init_decryption_and_verification. enc_round_keys A pointer to round keys generated by a call to the aes_encrypt_key_sched function.

Remarks:

The IV (initial counter) must be supplied in the beginning of the state buffer when the AES_INIT flag is set. This routine uses 2 levels of (nested) DO loops.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_INVALID_MAC

File Name:

aes_ccm.s

Files Needed:

aes_encrypt.o, aes_ccm.o, aes_cbc_encrypt_and_mac.o, aes_ctr.o

Clock Cycles:

2463 - 4498

Code Example:

aes_ccm_verify_mac(state, mac, enc_round_keys);

© 2006 Microchip Technology Inc.

DS51468B-page 35

dsPIC30F Embedded Encryption Libraries User’s Guide 3.6.2

Triple Data Encryption Algorithm (TDES)

The Triple DES functions described in this section include the following: • • • • • • •

tdes_key_sched tdes_ecb_encrypt tdes_ecb_decrypt tdes_cbc_mac tdes_cbc_encrypt tdes_cbc_decrypt tdes_ctr_crypt

tdes_key_sched Function:

Computes individual round keys for encryption and decryption from two symmetric DES keys.

C Include:

tdes.h

ASM Include:

tdes.inc

Prototype:

extern unsigned short tdes_key_sched( unsigned short int *round_keys, const unsigned char *keys);

Arguments:

round_keys A pointer to store the round keys consisting of 128 16-bit words. keys A pointer to a 16-byte buffer containing two 64-bit DES keys.

DS51468B-page 36

Remarks:

TDES uses 32 64-bit subkeys to perform encryption and decryption. These subkeys are derived from two 64-bit symmetric keys. This function must be called to derive the subkeys from the symmetric keys before any encryption or decryption functions can be called. Once the subkeys are computed, they may be used in multiple calls to encryption and decryption functions.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS

File Name:

tdes.s

Files Needed:

tdes.o

Clock Cycles:

3390

Code Example:

tdes_key_sched(round_keys, key);

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library tdes_ecb_encrypt Function:

Performs TDES encryption in Electronic Code Book mode.

C Include:

tdes_ecb.h

ASM Include:

tdes_ecb.inc

Prototype:

extern unsigned short tdes_ecb_encrypt( unsigned char *out, const unsigned char *in, unsigned short in_byte_len, const unsigned short int *round_keys);

Arguments:

out A pointer to output storage that must be at least in_byte_len bytes in length. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 8 and 65528 inclusive. Must be a multiple of 8. round_keys A pointer to round keys generated by a call to the tdes_key_sched function.

Remarks:

Electronic Code Book mode is the simplest mode of operation for TDES. It encrypts each block of plain text independently. The in and out pointers may refer to the same memory location. An error code of MCL_ILLEGAL_SIZE is returned if in_byte_len is not a multiple of 8, or it is zero.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

tdes_ecb.s

Files Needed:

tdes.o, tdes_ecb.o

Clock Cycles:

(4748 * no. of blocks) + 68

Code Example:

tdes_ecb_encrypt(out, in, in_byte_len, round_keys);

tdes_ecb_decrypt Function:

Performs TDES decryption in Electronic Code Book mode.

C Include:

tdes_ecb.h

ASM Include:

tdes_ecb.inc

Prototype:

extern unsigned short tdes_ecb_decrypt( unsigned char *out, const unsigned char *in, unsigned short in_byte_len, const unsigned short int *round_keys);

Arguments:

out A pointer to output storage that must be at least in_byte_len bytes in length. in A pointer to input data in_byte_len bytes in length.

© 2006 Microchip Technology Inc.

DS51468B-page 37

dsPIC30F Embedded Encryption Libraries User’s Guide tdes_ecb_decrypt (Continued) in_byte_len Number of input bytes ranging between 8 and 65528 inclusive. Must be a multiple of 8. round_keys A pointer to decryption round keys generated by a call to the tdes_key_sched function. Remarks:

Electronic Code Book mode is the simplest mode of operation for TDES. It decrypts each block of plain text independently. The in and out pointers may refer to the same memory location. An error code of MCL_ILLEGAL_SIZE is returned if in_byte_len is not a multiple of 8, or it is zero.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

tdes_ecb.s

Files Needed:

tdes.o, tdes_ecb.o

Clock Cycles:

(4748 * no. of blocks) + 70

Code Example:

tdes_ecb_decrypt(out, in, in_byte_len, round_keys);

tdes_cbc_mac Function:

Calculate the CBC-MAC authentication code using TDES, specified in FIPS-113.

C Include:

tdes_cbc.h

ASM Include:

tdes_cbc.inc

Prototype:

extern unsigned short tdes_cbc_mac( unsigned char *state, unsigned char *out, const unsigned char *in, unsigned short int in_byte_len, const unsigned short int *round_keys, unsigned short int flags);

Arguments:

state A pointer to an 18-byte buffer of temporary storage space. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[18]; out A pointer to output storage; must be at least 8 bytes in length. This buffer is only used by the function if the TDES_FINISH flag is set. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. round_keys A pointer to round keys generated by a call to the tdes_key_sched function.

DS51468B-page 38

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library tdes_cbc_mac (Continued) flags The value of flags can be any combination of the following values (defined in tdes.h): TDES_INIT Initialize state TDES_DATA_ONLY Add input data TDES_FINISH Finish computation Remarks:

Computes the CBC-MAC authentication code as defined in FIPS 113. The function may be called one or more times in the computation of a single MAC value. Calling with the TDES_INIT flag resets the initial state. This must be performed at the beginning of the computation of any new MAC value. Calling with the TDES_DATA_ONLY flag processes additional data. This may be called zero or more times until all input data has been processed. Calling with TDES_FINISH completes processing the input data, finalizes the hash value and stores the result in the buffer out. If TDES_FINISH is set, and no data has been processed (in other words, in_byte_len has been zero on all calls since the one with TDES_INIT set), the function returns MCL_ILLEGAL_SIZE.

Return Value:

Can be one of these values (from ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

tdes_cbc.s

Files Needed:

tdes.o, tdes_cbc.o

Clock Cycles:

(4744 * no. of blocks) + 168

Code Example:

tdes_cbc_mac(state, out, in, in_byte_len, round_keys, TDES_INIT);

tdes_cbc_encrypt Function:

Encrypts using CBC mode, optionally applying PKCS #5 padding to the final block.

C Include:

tdes_cbc.h

ASM Include:

tdes_cbc.inc

Prototype:

extern unsigned short tdes_cbc_encrypt( unsigned char *state, unsigned char *out, unsigned short int *out_byte_len, const unsigned char *in, unsigned short int in_byte_len, const unsigned short int *round_keys, unsigned short int flags);

Arguments:

state A pointer to an 18-byte buffer of temporary storage space. If the TDES_INIT flag is set, the first 8 bytes of the buffer must contain the Initialization Vector. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[18]; out A pointer to output storage. See below for length considerations.

© 2006 Microchip Technology Inc.

DS51468B-page 39

dsPIC30F Embedded Encryption Libraries User’s Guide tdes_cbc_encrypt (Continued) out_byte_len On success, this will point to the number of output bytes returned. Apart from one exception noted below, this will be in_byte_len. The exception occurs in processing the last block of plain text. Padding added by this function through the use of the TDES_INTERNAL_PAD flag may increase the length of the output. If TDES_FINISH and TDES_INTERNAL_PAD are both set, the length of the output will be in_byte_len plus 8 if in_byte_len is divisible by 8. Otherwise, the length will be in_byte_len rounded up so that out_byte_len is divisible by 8. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. Must be a multiple of 8 unless TDES_FINISH and TDES_INTERNAL_PAD are both set. round_keys A pointer to round keys generated by a call to the tdes_key_sched function. flags The value of flags can be any combination of these values (from tdes.h): TDES_INIT Initialize state TDES_DATA_ONLY Add input data TDES_FINISH Finish computation TDES_INTERNAL_PAD Apply internal padding

DS51468B-page 40

Remarks:

The in and out pointers may refer to the same memory location, so long as there is enough memory allocated at this location to hold the output data. If TDES_FINISH is set, and no data has been processed (in other words, in_byte_len has been zero on all calls since the one with TDES_INIT set), the function returns MCL_ILLEGAL_SIZE.

Return Value:

The return value can be one of these values (from ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

tdes_cbc.s

Files Needed:

tdes.o, tdes_cbc.o

Clock Cycles:

(4760 * no. of blocks) + 160 (no padding)

Code Example:

tdes_cbc_encrypt(state, out, out_byte_len, in, in_byte_len, round_keys, TDES_INIT);

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library tdes_cbc_decrypt Function:

Decrypts using CBC mode, optionally removing PKCS #5 padding from the final block.

C Include:

tdes_cbc.h

ASM Include:

tdes_cbc.inc

Prototype:

extern unsigned short tdes_cbc_decrypt( unsigned char *state, unsigned char *out, unsigned short int *out_byte_len, const unsigned char *in, unsigned short int in_byte_len, const unsigned short int *round_keys, unsigned short int flags);

Arguments:

state A pointer to a 16-byte buffer of temporary storage space. If the TDES_INIT flag is set, the first 8 bytes of the buffer must contain the Initialization Vector. This buffer must be allocated as follows: unsigned char __attribute__ ((aligned (2))) state[16]; out A pointer to output storage. See below for length considerations. out_byte_len On success, this will point to the number of output bytes returned. Apart from one exception noted below, this will be in_byte_len. The exception occurs in processing the last block of ciphertext. Padding stripped by this function through the use of the TDES_INTERNAL_PAD flag decreases the length of the output. If TDES_FINISH and TDES_INTERNAL_PAD are both set, the length of the output is in the range in_byte_len minus 8 to in_byte_len minus 1. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65528 inclusive. Must be a multiple of 8. round_keys A pointer to round keys generated by a call to the tdes_key_sched function. flags The value of flags can be any combination of the following values (defined in tdes.h): TDES_INIT Initialize state TDES_DATA_ONLY Add input data TDES_FINISH Finish computation TDES_INTERNAL_PAD Strip internal padding

Remarks:

The in and out pointers may refer to the same memory location. An error code of MCL_ILLEGAL_SIZE is returned if in_byte_len is not a multiple of 8, or is zero. An error code of MCL_ILLEGAL_PADDING is returned if the padding is incorrect.

Return Value:

The return value can be one of the following values (defined in ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE MCL_ILLEGAL_PADDING

© 2006 Microchip Technology Inc.

DS51468B-page 41

dsPIC30F Embedded Encryption Libraries User’s Guide tdes_cbc_decrypt (Continued) File Name:

tdes_cbc.s

Files Needed:

tdes.o, tdes_cbc.o

Clock Cycles:

(4768 * no. of blocks) + 141 (no padding)

Code Example:

tdes_cbc_decrypt(state, out, out_byte_len, in, in_byte_len, round_keys, TDES_INIT);

tdes_ctr_crypt Function:

Encrypt or decrypt using CTR mode.

C Include:

tdes_ctr.h

ASM Include:

tdes_ctr.inc

Prototype:

extern unsigned short tdes_ctr_crypt( unsigned char *state, unsigned char *out, const unsigned char *in, unsigned short int in_byte_len, const unsigned short int *round_keys, unsigned short int flags);

Arguments:

state A pointer to an 18-byte buffer of temporary storage space. If the TDES_INIT flag is set, the first 8 bytes of the buffer must contain the Initialization Vector. This buffer must be allocated as follows: unsigned char_attribute_ ((aligned(2))) state[18]; out A pointer to output storage that is in_byte_len bytes in length. in A pointer to input data in_byte_len bytes in length. in_byte_len Number of input bytes ranging between 0 and 65535 inclusive. round_keys A pointer to round keys generated by a call to the tdes_key_sched function. flags The value of flags can be any combination of these values (defined in tdes.h): TDES_INIT Initialize state TDES_DATA_ONLY Add input data TDES_FINISH Finish computation

DS51468B-page 42

Remarks:

The in and out pointers may refer to the same memory location. This function is used to perform both encryption and decryption. If TDES_FINISH is set, and no data has been processed (in other words, in_byte_len has been zero on all calls since the one with TDES_INIT set), the function returns MCL_ILLEGAL_SIZE.

Return Value:

The return value can be one of these values (from ret_codes.h): MCL_SUCCESS MCL_ILLEGAL_SIZE

File Name:

tdes_ctr.s

Files Needed:

tdes.o, tdes_ctr.o

Clock Cycles:

(4793 * no. of blocks) + 113

Code Example:

tdes_ctr_crypt(state, out, in, in_byte_len, round_keys, TDES_INIT);

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Chapter 4. dsPIC30F Asymmetric Key Embedded Encryption Library 4.1

INTRODUCTION This chapter provides information required to start using the dsPIC DSC Asymmetric Key Embedded Encryption Library. Chapter 5. “Asymmetric Key Encryption Utilities” provides information on operational aspects of the asymmetric key functions packaged in this library. Chapter 6. “Hash and Auxiliary Functions”, provides information on operational aspects of hash functions and random number generators provided in this library.

4.2

HIGHLIGHTS This chapter covers the following topics: • Library Software Contents • Using the Library • Rebuilding the Library

4.3

LIBRARY SOFTWARE CONTENTS Upon installation of the library, the following files and folders will be extracted under the folder named “dsPICAsymCryptoLib”: • doc This folder contains this User Guide document in PDF format. • lib This folder contains the pre-compiled library archive file, named libAsymCrypto.a that contains all the object files for the sources used to build the library. Another library file, "libAsymCryptoSmall.a", has also been provided. It is described in Section 4.4.1 “Building Applications with the Library”. • include\c This folder contains C header files for each object file within the library archive • include\asm This folder contains Assembler include files for each object file within the library archive file. • examples This folder contains various code examples in C that demonstrate library usage. Please read the “readme.txt” file provided with the release version of your library for further details. This file resides in the folder named “dsPICAsymCryptoLib”. The dsPIC30F Asymmetric Key Embedded Encryption Library archive contains pre-compiled object files created by assembling the source files. The code size (in bytes) for each object file is provided in Table 4-1. An object file is linked into an application only once, even if multiple functions from this object file are invoked. Further, if any object files are unused, they will not be linked into the application, though they are present in the library archive file.

© 2006 Microchip Technology Inc.

DS51468B-page 43

dsPIC30F Embedded Encryption Libraries User’s Guide TABLE 4-1:

ASYMMETRIC LIBRARY COMPOSITION

Algorithm Rivest Shamir Adleman (RSA) Diffie-Hellman Digital Signature Algorithm (DSA) Big Integer Arithmetic Package (Internal Functions) Secure Hash Algorithm (SHA-1) Message Digest Algorithm (MD5) ANSI X9.82

4.4

Library Functions

Object File

Size in Bytes

Encryption and Decryption Signing and Verification Chinese Remainder Theorem Key Agreement Protocol Signing and Verification

rsa_enc_dec.o rsa_sign_ver.o rsa_crt.o dh.o dsa.o

717 789 411 600 2391

Modular Arithmetic Functions Modular Arithmetic Inverse Functions Montgomery Arithmetic Functions SHA-1

math.o math_mod_inv.o

927 495

mont.o sha1.o

549 909

MD5

md5.o

1428

Deterministic Random Bit Generator

drbg.o

441

USING THE LIBRARY 4.4.1

Building Applications with the Library

Building an application which utilizes this library requires typically three files. These are: • The pre-compiled library archive file, named “libAsymCrypto.a”. Another library file, "libAsymCryptoSmall.a", has also been provided. This library contains all the functions except SHA-1, MD5 and the DRBG (X9.82). This file is provided to enable interoperability with the dsPIC30F Symmetric Key Embedded Encryption Library. Note that the Symmetric library also offers the SHA-1, MD5 and the DRBG library functions. • A C header file (or Assembler Include file) that is specified in the description of the function in this guide. The C header file is located in the “include\c” path under the folder where this library is installed. The Assembler include file is located in the “include\asm” path under the folder where this library is installed. These files provide the function prototypes, #defines and typedefs used by the library. • ret_codes.h file for development in C, or ret_codes.inc file for development in assembly-language These files define various return codes that specify a successful or failed operation. When compiling an application, the C header file must be referenced (using #include) by all source files which call a function in the Library or use its symbols or typedefs. When linking an application, “libAsymCrypto.a” must be provided as an input to the linker (using the --library or -l linker switch) so that the functions used by the application may be linked into the application. The linker will place the functions of the library into a special text section named “.libAsymCrypto”. This may be seen by looking at the map file generated by the linker.

DS51468B-page 44

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library 4.4.2

Memory Models

The dsPIC30F Asymmetric Key Embedded Encryption Library functions were developed purely in assembly language and the library was built using the assembler and linker tools in the MPLAB C30 tool suite. The entire library resides within a section named “.libAsymCrypto”. RCALL instructions have been used within the library functions to call other library functions. Hence, the library follows a small code model.

4.4.3

Library Function Calling Convention

All, but the functions in the following object modules within the dsPIC30F Asymmetric Key Embedded Encryption Library are compliant with the C compatibility guidelines for the dsPIC30F DSC: • math.o • math_mod_inv.o • mont.o The functions in these three object files are only needed internal to the library and their prototypes are not documented for use external to the library functions. The remaining functions follow the function call conventions documented in the “MPLAB C30 Compiler User’s Guide” (DS51217). Specifically, functions may use the first eight working registers (W0 through W7) as function arguments. Any additional function arguments are passed through the stack. The working registers W0 to W7 are treated as scratch memory, and their values may not be preserved after the function call. On the other hand, if any of the working registers W8 to W13 are used by a function, the working register is first saved, the register is used, and then its original value is restored upon function return. The return value of a (non void) function is available in working register W0 (also referred to as WREG). When needed, the run time software stack is used following the C system stack rules described in the “MPLAB C30 Compiler User’s Guide”. Based on these guidelines, the object modules of the library can be linked to either a C program, an assembly program, or a program which combines code in both languages.

4.4.4

Data Types

The operations performed by the dsPIC30F Asymmetric Key Embedded Encryption Library have been designed to take advantage of the DSP instruction set and architectural features of the dsPIC30F DSC. However, as one may expect in an encryption application, none of the computations use floating-point, fractional or signed integer arithmetic. All mathematical operations are perform using unsigned integer arithmetic. To achieve this end, all saturation and rounding modes supported by the accumulators are either disabled or not used. If MAC-class of instructions are used, they are used in unsigned integer mode.

© 2006 Microchip Technology Inc.

DS51468B-page 45

dsPIC30F Embedded Encryption Libraries User’s Guide 4.4.5

Data Memory Usage

The dsPIC30F Asymmetric Key Embedded Encryption Library performs no allocation of RAM, and leaves this task to you. If you do not allocate the appropriate amount of memory and align the data properly, undesired results will occur when the function executes. In addition, to minimize execution time, the library may not perform extensive checking on the provided function arguments (including pointers to data memory), to determine if they are valid. Many functions accept data pointers as function arguments, which contain the data to be operated on, and typically also the location to store the result. For convenience, most functions in the library expect their input arguments to be allocated in the default RAM memory space (X-Data or Y-Data), and the output to be stored back into the default RAM memory space. However, the more computational intensive functions require that some operands reside in X-Data and Y-Data, so that the operation can take advantage of the dual data fetch capability of the dsPIC30F architecture.

4.4.6

CORCON Register Usage

Many functions of the dsPIC30F Asymmetric Key Embedded Encryption Library place the dsPIC30F device into a special operating mode by modifying the CORCON register. On the entry of these functions, the CORCON register is NOT pushed to the stack. It is simply modified to correctly perform the desired operation. Likewise, the CORCON register is not restored to its original value. This mechanism allows the library to execute as correctly and quickly as possible. The application should save CORCON before calling a library function and restore it upon return, if the library function description indicates that CORCON will be modified. When the CORCON register is modified, it is typically set such that the dsPIC30F operates in the following mode: • • • •

DSP multiplies are set to unsigned integer data Accumulator saturation is disabled for Accumulator A and Accumulator B Data Space Write Saturation is disabled. Program Space Visibility disabled

For a detailed explanation of the CORCON register and its effects, refer to the “dsPIC30F Family Reference Manual” (DS70046).

4.4.7

Integrating with Interrupts and an RTOS

The dsPIC30F Asymmetric Key Embedded Encryption Library may easily be integrated into an application which utilizes interrupts or an RTOS, yet certain guidelines must be followed. To minimize execution time, the library utilizes DO loops, REPEAT loops and modulo addressing. Each of these components is a finite hardware resource on the dsPIC30F DSC, and the background code must consider the use of each resource when disrupting execution of a library function. When integrating with the library, you must examine the Function Profile of each function description to determine which resources are used. If a library function will be interrupted, it is your responsibility to save and restore the contents of all registers used by the function, including the state of the DO, REPEAT and special addressing hardware. Naturally this also includes saving and restoring the contents of the CORCON and Status registers.

DS51468B-page 46

© 2006 Microchip Technology Inc.

dsPIC30F EMBEDDED ENCRYPTION LIBRARIES USER’S GUIDE

Chapter 5. Asymmetric Key Encryption Utilities 5.1

INTRODUCTION This chapter describes the library functions provided in the dsPIC30F Asymmetric Key Embedded Encryption Library, that help in key agreement, signing and verification as well as directly protecting application data. These library functions include the Rivest Shamir Adleman (RSA) algorithm, Digital Signature Algorithm (DSA) and the Diffie-Hellman Key Agreement primitives.

5.2

HIGHLIGHTS This chapter covers the following topics: • General Primer on Asymmetric Functions • Specific Public Key Algorithms • Asymmetric Key Functions

5.3

GENERAL PRIMER ON ASYMMETRIC FUNCTIONS 5.3.1

Encryption

Public Key encryption is like symmetric encryption, in that the sender of the message encrypts it using an algorithm and a key, and the receiver decrypts it using an algorithm and a key. However, in the case of public key encryption, the encryption key and the decryption key are mathematically linked so that even if you know the encryption key, it’s very hard to work out the decryption key. Everyone can be given the encryption key (the public key) and the decryption key (the private key) will still remain secret. So, as long as I can be sure your public key belongs to you, and as long as you can be sure my public key belongs to me, we can communicate securely without having to transport a secret key between us in some physically secure way. This is the huge advantage of public key cryptography. However, it has some disadvantages. Because the public and private keys are mathematically linked, the public key has some mathematical structure, which an attacker can potentially exploit. Therefore, public key algorithms tend to have larger keys and to run slower than symmetric algorithms with equivalent strength. Standard practice for bulk encryption is to combine public key and symmetric operations. For example, if Alice wants to send a long message securely to Bob, she does the following: 1. She generates a key k for a symmetric algorithm. The key k is known as the session key. 2. She encrypts the session key k with Bob’s public key, and sends the encrypted key to Bob. 3. She secures (encrypts and/or authenticates) the messages with the session key k, and sends the resulting ciphertext to Bob.

© 2006 Microchip Technology Inc.

DS51468B-page 47

dsPIC30F Embedded Encryption Libraries User’s Guide Bob does the following: 1. He decrypts the encrypted key block, recovering k. 2. He then uses k to decrypt and/or verify the authentication on the message. The hybrid system outlined allows the flexibility of public key-based key distribution, with only a small performance hit compared to a fully symmetric system. Most of the existing protocols that use public key algorithms can be seen as examples of this kind of hybrid system; examples include SSL/TLS, IPSec (with IKE as the key exchange protocol), and S/MIME secure e-mail. All of these protocols have been carefully designed to fit the specific requirements of their environment. In general, developers should use existing protocols if possible, and be wary of designing custom cryptographic protocols as they can be prone to subtle errors which compromise their security.

5.3.2

Signing

Public key cryptosystems also provide for authentication, through the processes of signing and verification. A signature is a checksum that’s generated from a message using the signer’s private key. The process of verification involves the message, the signature, and the signer’s public key. A signature will only verify if: • The message has not been altered since it was signed; • The signature has not been altered since it was generated; • The correct public key is used. A significant difference between signatures and MACs arises from the asymmetric nature of public key cryptosystems. With symmetric MACs, anyone who can verify a MAC can also generate one. This makes it difficult to prove to a third party that a message came from the sender, rather than the person it was sent to. (Specialist hardware can reduce this risk – a sender can have a box that calculates MACs, a receiver can have a box with the same key that only verifies them – but this isn’t a universal solution.) With signatures, only one person can have generated the signature, and anyone can verify them; if need be, for example, I can show your signature to a judge. Since we would like to be able to sign arbitrary-length messages no matter what the length of the key, a common practice is to hash the message with an agreed-upon hash function before signing, and again before verifying. Therefore, if Alice wants to sign a message to Bob, she does the following. 1. She hashes the message M with an agreed hash function to obtain H. 2. She signs H with her private key a (we write this as Sgn(a,H)) to obtain the signature S. 3. She sends Bob M and S, and her public key A. To verify the signature, Bob does the following. 1. He receives A, M and S. 2. He hashes M to obtain H. 3. He uses the verification function Ver(A, H, S) to check that the signature is consistent with the message (represented by its hash) and Alice’s public key A. The function Ver outputs “valid” if the signature is valid, in other words if Alice has produced it using her private key and neither the message nor the signature has been altered in transit. Otherwise, it outputs “invalid”.

DS51468B-page 48

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library We summarize this discussion as follows. If Alice wants to encrypt and authenticate a message for Bob, she does the following: 1. She uses Bob’s public key to encrypt the message. (She wants only Bob to read the message. Encrypting it with Bob’s public key means that the recipient will need to use Bob’s private key, which only Bob has). 2. She uses her private key to sign the message. (She wants Bob to be sure that the message has come from her. Only she knows her private key, so only she can generate the signature. Bob, or anyone else, can verify the signature using Alice’s public key, and be sure that the message has come from Alice). 3. She sends the encrypted message and the signature to Bob. When Bob receives the message, he does the following: 1. Using his own private key, he decrypts the message. (He knows the message was intended for him, so he decrypts it using the private key, which is information that only he knows.) 2. Using Alice’s public key, he verifies the signature on the message. (To make sure the message came from Alice, he uses the public key to guarantee that the signature was generated with Alice’s private key.)

5.3.3

Key Agreement

Key agreement allows two users, Alice and Bob, to securely agree on a key k, but without either party explicitly generating and encrypting a key. It therefore differs superficially from the hybrid protocol outlined above, but can in fact be used in a very similar way. To secure a long message to Bob using Diffie-Hellman key exchange, Alice does the following. 1. She sends her public key A to Bob and receives his public key B. 2. She combines her private key a with Bob’s public key B, generating the shared secret S. The “magic” of Diffie-Hellman is that Bob, in his step 2 below, will generate exactly the same value for S. 3. She inputs S to some previously agreed key derivation function (for example, a simple hash function). The output from this function is the shared secret key k. 4. She uses k to secure the message. Bob does the following: 1. He sends his public key B to Alice and receives his public key A. 2. He combines his private key b with Alice’s public key A, generating the shared secret S. As noted above, this is the same as the value that Alice has calculated for S in her step 2. 3. He inputs S to some previously agreed key derivation function (for example, a simple hash function). The output from this function is the shared secret key k. 4. He uses k to decrypt and/or verify the authentication on the message. In general key agreement in less widely used than encryption, because with practical systems the operations (and particular public key operations) are often slower.

© 2006 Microchip Technology Inc.

DS51468B-page 49

dsPIC30F Embedded Encryption Libraries User’s Guide 5.3.4

System Parameters vs. Public Keys

Typically in public key algorithms there are several public mathematical quantities (and possibly also several private quantities). For many public key algorithms the creation of a few of the public quantities is a computationally intensive task, but once created, multiple parties can reuse them. We shall refer to such public quantities as system parameters. With respect to the toolkit provided, both Diffie-Hellman, and DSA have such system parameters, e.g. in DSA multiple parties may use the same p, q and g, but each party has its own public key y, and private key x. The RSA algorithm (also provided in the toolkit) has public quantities N and e, but it is not secure for multiple parties (who wish to keep secrets from each other) to reuse the same N. Multiple parties may use the same e, but since it is not computationally expensive to pick e, this is not thought of as a system parameter. Thus the RSA algorithm does not allow for useful system parameters, and all the public information is considered to be part of the public key (i.e., the two quantities N and e).

5.3.5

Key Formats

Public keys are often transported in standard formats, the most common of these being PKCS ASN.1 encodings. However keys may come in other formats (e.g. internally created keys). To make the toolkit as flexible as possible it is assumed that all keys are given as byte arrays in network byte order. The process of stripping an ASN.1 encoding to produce a byte array is not complex, and is left to applications engineers to implement (if required). The toolkit does not supply any functions for ASN.1 encoding handling.

5.3.6

Key Generation

Public key algorithms often have a computationally intensive part to their implementation, whether it is in system parameter generation or in public or private key generation. With the toolkit provided, the most computationally intensive operations involve large prime number generation, and occur in Diffie-Hellman parameter generation, DSA parameter generation and RSA key generation. These functions are therefore not supported on the dsPIC DSC processor itself. Instead users may download and customize freely available Open SSL source code to their desktop or workstation and produce the desired quantities. In the case of RSA key generation the data involves the RSA private key, and so great care should be taken when transporting the data from the place it is generated to the place it is used.

DS51468B-page 50

© 2006 Microchip Technology Inc.

dsPIC30F Symmetric Key Embedded Encryption Library 5.4

SPECIFIC PUBLIC KEY ALGORITHMS 5.4.1

Encryption: RSA

This toolkit supports public key encryption using the RSA algorithm, as specified in PKCS#1 v1.5. This algorithm was invented in 1976 by Ron Rivest, Adi Shamir, and Len Adelman, and published in 1977. It is widely used, with many different implementations available, and has been standardized by many different industry, national, and international bodies. RSA key generation takes a parameter e, and then chooses two primes p, q which constitute (part of) the private key, and outputs N and e as the public key, where N=p*q. The RSA encryption primitive involves exponentiation of a message to the e’th power modulo N. Although p and q and the public exponent e are enough to allow for reasonably efficient decryption, the toolkit actually stores five quantities p, q, dp, dq, qinv as the private key (stored in one large array) to achieve faster decryption times. Decryption also involves modular exponentiation. The toolkit allows for two security strengths for RSA encryption, namely using a public modulus N of size 1024 bits (128 bytes), or a public modulus N of size 2048 bits (256 bytes), i.e., this length is taken as input to the RSA key generation, encryption and decryption functions. It should be noted that regardless of this choice the pseudorandom number generator used with encryption follows the ANSI X9.82 standard with the SHA-1 hash function. For RSA encryption to be secure, the message must be combined with some random padding before it is encrypted. It is therefore important to seed the pseudorandom number generator before calling the encryption function. The choice of padding and unpadding method converts RSA from an encryption primitive to an encryption scheme, analogous to the way that the choice of a mode of operation is necessary to convert a block cipher from a primitive that encrypts a single block to a scheme that can encrypt an entire message. The encryption scheme supported by this toolkit is known as PKCS#1 v1.5. It is the method of choice for many widely used protocols, such as SSL/TLS and WTLS. Recent results have shown that the RSA-PKCS#1 v1.5 encryption scheme may be vulnerable to certain attacks if used incorrectly. These attacks rely on an attacker constructing ciphertexts and submitting them for decryption, and gaining information from observing if the decryption fails due to unpadding errors. These attacks can be foiled by ensuring that a system does not return error messages to the sender of a message that would allow them to distinguish between a failure due to unpadding and a failure for other reasons. The toolkit conforms to this requirement. This toolkit performs both the RSA encryption and decryption, and the associated PKCS#1 padding and unpadding, internally. Implementers need not explicitly pad or unpad messages.

© 2006 Microchip Technology Inc.

DS51468B-page 51

dsPIC30F Embedded Encryption Libraries User’s Guide 5.4.2

Key Agreement: Diffie-Hellman

The toolkit provides the Diffie-Hellman key agreement protocol, as specified in PKCS#3. Diffie-Hellman parameter generation involves generating a large prime p and a large generator g. Diffie-Hellman key generation then involves choosing a random private key x, and exponentiating g to this power, modulo p, to form a public key y. The two parties wishing to share a key do this independently. Diffie-Hellman shared key creation then involves a further modular exponentiation of each other’s public key yi. In Diffie-Hellman key generation the PKCS#3 standard allows for the case when x is randomly chosen to be a specified bit length, and the case when x is randomly chosen to lie in the range 1