140
© 2006 Microchip Technology Inc. DS51468B dsPIC30F Embedded Encryption Libraries User’s Guide

dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

  • Upload
    lyhuong

  • View
    254

  • Download
    0

Embed Size (px)

Citation preview

Page 1: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

© 2006 Microchip Technology Inc. DS51468B

dsPIC30F EmbeddedEncryption Libraries

User’s Guide

Page 2: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow 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 deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS OR WAR-RANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED,WRITTEN OR ORAL, STATUTORY OR OTHERWISE,RELATED TO THE INFORMATION, INCLUDING BUT NOTLIMITED TO ITS CONDITION, QUALITY, PERFORMANCE,MERCHANTABILITY OR FITNESS FOR PURPOSE.Microchip disclaims all liability arising from this information andits use. Use of Microchip devices in life support and/or safetyapplications is entirely at the buyer’s risk, and the buyer agreesto defend, indemnify and hold harmless Microchip from any andall damages, claims, suits, or expenses resulting from suchuse. No licenses are conveyed, implicitly or otherwise, underany Microchip intellectual property rights.

DS51468B-page ii

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.

© 2006 Microchip Technology Inc.

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.

Page 3: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Table of Contents

Preface ..................................................................................................................1Chapter 1. Introduction

1.1 Introduction .................................................................................................... 71.2 Highlights ....................................................................................................... 71.3 Overview of Embedded Cryptographic Applications ...................................... 71.4 Using the dsPIC DSC Devices in Embedded Cryptographic Applications ..... 81.5 dsPIC30F Embedded Encryption Libraries .................................................... 8

Chapter 2. dsPIC30F Symmetric Key Embedded Encryption Library2.1 Introduction .................................................................................................... 92.2 Highlights ....................................................................................................... 92.3 Library Software Contents .............................................................................. 92.4 Using the Library .......................................................................................... 10

Chapter 3. Symmetric Key Encryption Utilities3.1 Introduction .................................................................................................. 133.2 Highlights ..................................................................................................... 133.3 Encrypting Messages: Modes of Operation and Padding ............................ 133.4 Message Authentication Modes ................................................................... 183.5 Combined Message Authentication and Encryption Modes ......................... 193.6 Symmetric Key Encryption/Decryption Functions ........................................ 20

Chapter 4. dsPIC30F Asymmetric Key Embedded Encryption Library4.1 Introduction .................................................................................................. 434.2 Highlights ..................................................................................................... 434.3 Library Software Contents ............................................................................ 434.4 Using the Library .......................................................................................... 44

Chapter 5. Asymmetric Key Encryption Utilities5.1 Introduction .................................................................................................. 475.2 Highlights ..................................................................................................... 475.3 General Primer on Asymmetric Functions ................................................... 475.4 Specific Public Key Algorithms ..................................................................... 515.5 Asymmetric Key Functions ........................................................................... 54

Chapter 6. Hash and Auxiliary Functions6.1 Introduction .................................................................................................. 676.2 Highlights ..................................................................................................... 676.3 Message Digest/Hash Functions ................................................................. 676.4 Auxiliary Functions ....................................................................................... 70

© 2006 Microchip Technology Inc. DS51468B-page iii

Page 4: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

Appendix A. Symmetric Function ExamplesA.1 Introduction .................................................................................................. 75A.2 Highlights ..................................................................................................... 75A.3 Symmetric Function Examples .................................................................... 75

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

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

Appendix D. ReferencesD.1 Introduction ................................................................................................ 131D.2 Highlights ................................................................................................... 131D.3 References to Federal Information Processing Standards (FIPS)

and Other Specifications ...................................................................... 131D.4 References to Textbooks on Modern Cryptographic Practices

and Algorithms ...................................................................................... 132

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

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

DS51468B-page iv © 2006 Microchip Technology Inc.

Page 5: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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

Page 6: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 gov-ernmental 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:

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:

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

XXXXX = The document number.

A = The revision level of the document.

DS51468B-page 2 © 2006 Microchip Technology Inc.

Page 7: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 GuidesThis 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 SiteThe 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

Page 8: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

Page 9: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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

Page 10: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

Page 11: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 cur-rency 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 con-nected 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 communica-tion 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 communi-cation 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

Page 12: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 candi-date 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 LibraryThis 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 LibraryThis 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.

Page 13: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Chapter 2. dsPIC30F Symmetric Key EmbeddedEncryption 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”:

• docThis folder contains this User’s Guide document in PDF format.

• libThis 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\cThis folder contains C header files for each object file within the library archive.

• include\asmThis folder contains assembler include files for each object file within the library archive file.

• examplesThis 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

Page 14: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

TABLE 2-1: SYMMETRIC LIBRARY COMPOSITION

2.4 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.

Algorithm Library Functions Object FileSize

in Bytes

Advanced EncryptionStandard (AES)

Basic Encryption Function aes_encrypt.o 2505

Basic Decryption Function aes_decrypt.o 2895Electronic Code Book Mode aes_ecb.o 234Cipher Block ChainingEncryption and MessageAuthentication(CBC-MAC) Mode

aes_cbc_encrypt_and_mac.o 663

CBC Mode Decryption aes_cbc_decrypt.o 357Counter Mode aes_ctr.o 348Combined CBC MAC andCounter Mode

aes_ccm.o 930

Triple DataEncryption Algorithm(Triple DES)

Basic Encryption andDecryption Functions

tdes.o 8892

Electronic Code Book Mode tdes_ecb.o 120

Cipher Block Chaining Mode tdes_cbc.o 903Counter Mode tdes_ctr.o 348

Secure HashAlgorithm (SHA-1)

SHA-1 sha1.o 909

Message DigestAlgorithm (MD5)

MD5 md5.o 1428

ANSI X9.82 Deterministic Random BitGenerator

drbg.o 441

DS51468B-page 10 © 2006 Microchip Technology Inc.

Page 15: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 devel-oped 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 regis-ters 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 architec-tural 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

Page 16: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

Page 17: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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:

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

3.3 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: 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.

© 2006 Microchip Technology Inc. DS51468B-page 13

Page 18: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 stan-dards 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 encryp-tion 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.

Page 19: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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: 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.

© 2006 Microchip Technology Inc. DS51468B-page 15

Page 20: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

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.

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

DS51468B-page 16 © 2006 Microchip Technology Inc.

Page 21: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 authenti-cate 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

Page 22: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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/fips-pubs/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.

Page 23: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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, allow-ing an attacker to forge MACs on unseen messages. Therefore, a common recommen-dation 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,000- 1,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.

3.5.1 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 secu-rity 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,000- 1,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.

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

© 2006 Microchip Technology Inc. DS51468B-page 19

Page 24: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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_schedFunction: 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_keysA pointer to a buffer consisting of 44 32-bit words to hold the encryption round keys.

keyA pointer to the 128-bit encryption key.

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);

DS51468B-page 20 © 2006 Microchip Technology Inc.

Page 25: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

aes_decrypt_key_schedFunction: 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_keysA pointer to a buffer consisting of 44 32-bit words to hold the decryption round keys.

enc_round_keysA 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_encryptFunction: 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: outA pointer to output block storage that must be at least in_byte_len bytes in length.

inA pointer to input block storage in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 16 and 65520 inclusive. Must be a multiple of 16.

enc_round_keysA pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function.

© 2006 Microchip Technology Inc. DS51468B-page 21

Page 26: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

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_decryptFunction: 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: outA pointer to output block storage that must be at least in_byte_len bytes in length.

inA pointer to input block storage in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 16 and 65520 inclusive. Must be a multiple of 16.

dec_round_keysA pointer to decryption round keys generated by a call to the aes_decrypt_key_sched function.

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);

aes_ecb_encrypt (Continued)

DS51468B-page 22 © 2006 Microchip Technology Inc.

Page 27: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

aes_cbc_macFunction: 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: stateA pointer to a 34-byte buffer of temporary storage space. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2))) state[34];

outA 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.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65535 inclusive.

enc_round_keysA pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function.

flagsThe value of flags can be any combination of the following values (defined in aes.h):

AES_INIT Initialize stateAES_DATA_ONLY Add input dataAES_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_SUCCESSMCL_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

Page 28: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

aes_cbc_encryptFunction: 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: stateA 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];

outA pointer to output storage. See below for length considerations.

out_byte_lenOn success, this will point to the number of output bytes returned. Apart from one exception noted below, this will be in_byte_lenThe 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.

inA pointer to input storage in_byte_len bytes in length.

in_byte_lenNumber 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_keysA pointer to decryption round keys generated by a call to the aes_encrypt_key_sched function.

flagsThe value of flags can be any combination of the following values (defined in aes.h):

AES_INIT Initialize stateAES_DATA_ONLY Add input dataAES_FINISH Finish computationAES_INTERNAL_PAD Apply padding internally

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 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.

DS51468B-page 24 © 2006 Microchip Technology Inc.

Page 29: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

Return Value: The return value can be one of the following values (defined in ret_codes.h):MCL_SUCCESSMCL_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_encrypt (Continued)

aes_cbc_decryptFunction: 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: stateA 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];

outA pointer to output storage. See below for length considerations.

out_byte_lenOn 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.

inA pointer to input storage in_byte_len bytes in length.

in_byte_lenNumber 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_keysA pointer to decryption round keys generated by a call to the aes_decrypt_key_sched function.

© 2006 Microchip Technology Inc. DS51468B-page 25

Page 30: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

flagsThe value of flags can be any combination of the following values(defined in aes.h):

AES_INIT Initialize stateAES_DATA_ONLY Add input dataAES_FINISH Finish computationAES_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_SUCCESSMCL_ILLEGAL_SIZEMCL_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_cryptFunction: 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: stateA 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];

outA pointer to output storage that is in_byte_len bytes in length.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65535 inclusive.

enc_round_keysA pointer to round keys generated by a call to the aes_encrypt_key_sched function.

aes_cbc_decrypt (Continued)

DS51468B-page 26 © 2006 Microchip Technology Inc.

Page 31: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

flagsThe value of flags can be any combination of the following values (defined in aes.h):

AES_INIT Initialize stateAES_DATA_ONLY Add input dataAES_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_SUCCESSMCL_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);

aes_ctr_crypt (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 27

Page 32: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

Page 33: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

aes_ccm_init_encryption_and_macFunction: 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: stateA 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_lenA 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_lenThe length of the length data contained in AD_byte_len. Must be between 0 and 8 inclusive.

AED_byte_lenA 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_lenThe length of the length data contained in AED_byte_len. Must be between 2 and 8 inclusive.

nonceA pointer to the nonce.

nonce_byte_lenThe length in bytes of the nonce, equal to 15 - AEDlen_byte_len.

MAC_byte_lenThe 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_keysA pointer to encryption round keys generated by a call to the aes_encrypt_key_sched function.

© 2006 Microchip Technology Inc. DS51468B-page 29

Page 34: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

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, orthe 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_SUCCESSMCL_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_encryption_and_mac (Continued)

aes_ccm_init_decryption_and_verificationFunction: 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: stateA 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_lenA 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_lenThe length of the length data contained in AD_byte_len. Must be 0-8 inclusive.

DS51468B-page 30 © 2006 Microchip Technology Inc.

Page 35: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

AED_byte_lenA 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_lenThe length of the length data contained in AED_byte_len. Must be 2-8 inclusive.

nonceA pointer to the nonce.

nonce_byte_lenThe length in bytes of the nonce, equal to 15 - AEDlen_byte_len.

MAC_byte_lenThe 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_keysA 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_SUCCESSMCL_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);

aes_ccm_init_decryption_and_verification (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 31

Page 36: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

aes_ccm_input_ADFunction: 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: stateA 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_lenA pointer to the number of output bytes returned ranging between 0 and 65535 inclusive.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65535 inclusive.

enc_round_keysA pointer to round keys generated by a call to the aes_encrypt_key_sched function.

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);

DS51468B-page 32 © 2006 Microchip Technology Inc.

Page 37: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

aes_ccm_crypt_AEDFunction: 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: stateA 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.

outA pointer to output storage that is in_byte_len bytes in length.

out_byte_lenA pointer to the number of output bytes returned ranging between 0 and 65535 inclusive.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65535 inclusive.

enc_round_keysA pointer to round keys generated by a call to the aes_encrypt_key_sched function.

Remarks: 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.

© 2006 Microchip Technology Inc. DS51468B-page 33

Page 38: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

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_crypt_AED (Continued)

aes_ccm_get_macFunction: 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: stateA 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.

macA 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_keysA 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

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);

DS51468B-page 34 © 2006 Microchip Technology Inc.

Page 39: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

aes_ccm_verify_macFunction: 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: stateA 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.

macA 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_keysA 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_SUCCESSMCL_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

Page 40: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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_schedFunction: 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_keysA pointer to store the round keys consisting of 128 16-bit words.

keysA pointer to a 16-byte buffer containing two 64-bit DES keys.

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);

DS51468B-page 36 © 2006 Microchip Technology Inc.

Page 41: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

tdes_ecb_encryptFunction: 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: outA pointer to output storage that must be at least in_byte_len bytes in length.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 8 and 65528 inclusive. Must be a multiple of 8.

round_keysA 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_decryptFunction: 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: outA pointer to output storage that must be at least in_byte_len bytes in length.

inA pointer to input data in_byte_len bytes in length.

© 2006 Microchip Technology Inc. DS51468B-page 37

Page 42: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

in_byte_lenNumber of input bytes ranging between 8 and 65528 inclusive. Must be a multiple of 8.

round_keysA 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_SUCCESSMCL_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_ecb_decrypt (Continued)

tdes_cbc_macFunction: 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: stateA pointer to an 18-byte buffer of temporary storage space. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2))) state[18];

outA 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.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65535 inclusive.

round_keysA pointer to round keys generated by a call to the tdes_key_sched function.

DS51468B-page 38 © 2006 Microchip Technology Inc.

Page 43: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

flagsThe value of flags can be any combination of the following values (defined in tdes.h):

TDES_INIT Initialize stateTDES_DATA_ONLY Add input dataTDES_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_SUCCESSMCL_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_mac (Continued)

tdes_cbc_encryptFunction: 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: stateA 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];

outA pointer to output storage. See below for length considerations.

© 2006 Microchip Technology Inc. DS51468B-page 39

Page 44: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

out_byte_lenOn 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.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber 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_keysA pointer to round keys generated by a call to the tdes_key_sched function.

flagsThe value of flags can be any combination of these values (from tdes.h):

TDES_INIT Initialize stateTDES_DATA_ONLY Add input dataTDES_FINISH Finish computationTDES_INTERNAL_PAD Apply internal padding

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_SUCCESSMCL_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);

tdes_cbc_encrypt (Continued)

DS51468B-page 40 © 2006 Microchip Technology Inc.

Page 45: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

tdes_cbc_decryptFunction: 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: stateA 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];

outA pointer to output storage. See below for length considerations.

out_byte_lenOn 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.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65528 inclusive. Must be a multiple of 8.

round_keysA pointer to round keys generated by a call to the tdes_key_sched function.

flagsThe value of flags can be any combination of the following values (defined in tdes.h):

TDES_INIT Initialize stateTDES_DATA_ONLY Add input dataTDES_FINISH Finish computationTDES_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_SUCCESSMCL_ILLEGAL_SIZEMCL_ILLEGAL_PADDING

© 2006 Microchip Technology Inc. DS51468B-page 41

Page 46: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

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_cbc_decrypt (Continued)

tdes_ctr_cryptFunction: 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: stateA 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];

outA pointer to output storage that is in_byte_len bytes in length.

inA pointer to input data in_byte_len bytes in length.

in_byte_lenNumber of input bytes ranging between 0 and 65535 inclusive.

round_keysA pointer to round keys generated by a call to the tdes_key_sched function.

flagsThe value of flags can be any combination of these values (defined in tdes.h):

TDES_INIT Initialize stateTDES_DATA_ONLY Add input dataTDES_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 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_SUCCESSMCL_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);

DS51468B-page 42 © 2006 Microchip Technology Inc.

Page 47: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Chapter 4. dsPIC30F Asymmetric Key EmbeddedEncryption 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 Utili-ties” provides information on operational aspects of the asymmetric key functions packaged in this library. Chapter 6. “Hash and Auxiliary Functions”, provides infor-mation on operational aspects of hash functions and random number generators pro-vided 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”:

• docThis folder contains this User Guide document in PDF format.

• libThis 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\cThis folder contains C header files for each object file within the library archive

• include\asmThis folder contains Assembler include files for each object file within the library archive file.

• examplesThis 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

Page 48: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

TABLE 4-1: ASYMMETRIC LIBRARY COMPOSITION

4.4 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.

Algorithm Library Functions Object FileSize

in Bytes

Rivest Shamir Adleman (RSA)

Encryption and Decryption rsa_enc_dec.o 717

Signing and Verification rsa_sign_ver.o 789Chinese Remainder Theorem rsa_crt.o 411

Diffie-Hellman Key Agreement Protocol dh.o 600

Digital SignatureAlgorithm (DSA)

Signing and Verification dsa.o 2391

Big Integer Arithmetic Package (InternalFunctions)

Modular Arithmetic Functions math.o 927Modular Arithmetic InverseFunctions

math_mod_inv.o 495

Montgomery Arithmetic Functions mont.o 549Secure HashAlgorithm (SHA-1)

SHA-1 sha1.o 909

Message DigestAlgorithm (MD5)

MD5 md5.o 1428

ANSI X9.82 Deterministic Random BitGenerator

drbg.o 441

DS51468B-page 44 © 2006 Microchip Technology Inc.

Page 49: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 regis-ters 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 architec-tural 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

Page 50: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

Page 51: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 encryp-tion 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

Page 52: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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.

Page 53: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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

Page 54: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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. inter-nally 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 implementa-tion, whether it is in system parameter generation or in public or private key genera-tion. 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.

Page 55: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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

Page 56: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

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 cre-ation 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<x<p-1. This functionality is supported by toolkit, however in the case when x is chosen to be a fixed bit length, the toolkit insists on this length being at least 160 bits long, since Diffie-Hellman is insecure for choices less than this.

The toolkit allows for two security strengths for Diffie-Hellman key exchange, namely using a public prime p of size 1024 bits (128 bytes), or a public prime p of size 2048 bits (256 bytes), i.e., this length is taken as input to the Diffie-Hellman parameter generation, key generation, and shared key creation functions. It should be noted that regardless of this choice the pseudorandom number generator used within key generation follows the ANSI X9.82 standard with the SHA-1 hash function.

Diffie-Hellman parameter generation requires the generation of large prime numbers, which is a highly computationally intensive task. This toolkit therefore does not support Diffie-Hellman parameter generation for the dsPIC DSC processor. Instead users may download and customize freely available Open SSL source code to their desktop or workstation and generate Diffie-Hellman parameters which may be eventu-ally imported into dsPIC DSC based devices.

5.4.3 Digital Signatures: RSA

This toolkit supports the PKCS#1_v1.5 signature scheme for RSA. This signature scheme takes as input the private key, a hash H of the message to be signed, and a string that identifies the hash function. The byte strings for the commonly used hash functions are included in the RSA header file.

Note that the PKCS#1_v1.5 signature differs from the PKCS#1_v1.5 encryption scheme mentioned above, and the attacks that apply to the encryption scheme do not appear to have any relevance to the signature scheme.

The key generation for RSA signing is exactly as in the encryption case, i.e., the pub-lic key is (N, e) and the private key is (p, q, dp, dq, qinv). Both signing and verification again involve modular exponentiation. RSA signing, being the private operation, is very similar to RSA decryption, the major differences being that the hash identification byte string is also passed in, and the PKCS#1 padding does not involve adding ran-dom numbers, so the pseudorandom number generator need not be seeded prior to signing. RSA verification, being the public operation, is very similar to RSA encryption, the major difference being that the message hash information is also passed in, so the function simply returns whether or not the (message hash, signature) pair is valid.

DS51468B-page 52 © 2006 Microchip Technology Inc.

Page 57: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

The toolkit allows for two security strengths for RSA signing, 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, signing and verifi-cation functions. It should be noted that the hash function choice is independent of the modulus size choice, and users should aim to balance these two strengths, since an attacker can either try to factor the modulus, or try to find a hash-function collision. For example the SHA-1 hash function has comparable security to a 1024-bit modulus N (so it is appropriate to use these two to produce RSA signatures), however it is much easier to find SHA-1 collisions than to factor a 2048-bit modulus N (so we do not recommend using these two to produce RSA signatures).

This toolkit performs both the RSA signing and verification, and the associated PKCS#1 padding and unpadding, internally. Implementers need not explicitly pad or unpad messages, but they should produce the message hash.

As mentioned earlier, RSA key generation requires the generation of large prime numbers. This is a highly computationally intensive task. This toolkit therefore does not support RSA key generation directly for the dsPIC DSC processor. Instead users may download and customize freely available Open SSL source code to their desktop or workstation and produce the desired quantities. As always care should be taken transporting any private key material from the place it is generated to the place it is used.

5.4.4 Digital Signatures: DSA

This toolkit supports the FIPS 186-2 standard for DSA. DSA parameter generation involves generating a large prime p, a smaller prime q that divides p-1, and a large generator g. The primes p and q must be 1024 bits and 160 bits respectively. DSA key generation then involves choosing a random private key x, 0 < x < q-1, and exponenti-ating g to this power, modulo p, to form a public key y. DSA signing is performed on the SHA-1 hash of the message, and involves choosing an ephemeral key k, 0 < k < q-1, thus it is very important to have a properly seeded pseudorandom number gener-ator prior to calling both DSA key generation and DSA signing. The output of DSA signing is two 20-byte quantities r and s. DSA verification involves modular exponentiation of g and y modulo p.

Notice that there is only one supported modulus size to use with DSA, and the choice of hash function is not optional; it must be SHA-1.

DSA parameter generation requires the generation of large prime numbers, which is a highly computationally intensive task. This toolkit therefore does not support DSA parameter generation for the dsPIC DSC processor. Instead users may download and customize freely available Open SSL source code to their desktop or workstation and generate DSA parameters for import into dsPIC DSC based devices.

© 2006 Microchip Technology Inc. DS51468B-page 53

Page 58: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

5.5 ASYMMETRIC KEY FUNCTIONS

This section identifies individual asymmetric key cryptographic functions. Most of these functions require working buffers, one in x-data space, and the other in y-data space, since many functions utilize the MAC instruction on the dsPIC DSC device. In memory restricted situations it may be preferable to use these buffers both as working buffers, and as buffers that hold information returned by the cryptographic function. For each buffer used to hold information returned by the cryptographic function, any placement conditions that would prevent correct cryptographic operation are pointed out. For example, a return buffer might not be able to overlap with the last 20 bytes of the x-data working buffer.

Most functions are designed to automatically return error codes if such buffers are incorrectly placed.

5.5.1 Diffie-Hellman (DH)

The following functions are provided for the Diffie-Hellman Key Agreement Protocol:

• dh_generate_keys

• dh_create_shared_key

Examples of these functions are provided in Appendix B. “Asymmetric Function Examples”.

dh_generate_keysFunction: Generate a Diffie-Hellman Public-Private Keypair.

C Include: dh.h

ASM Include: dh.inc

Prototype: extern unsigned short int dh_generate_keys(unsigned char *pubkey, unsigned char *privkey, unsigned short int privkey_bit_len,const unsigned char *g,const unsigned char *p,unsigned short int p_byte_len,unsigned char *xbuf,unsigned char *ybuf);

Arguments: pubkeyA pointer to k bytes to hold the returned public key in Most Significant Byte first order. This buffer may not overlap the last k bytes of xbuf.

privkeyA pointer to ceil(privkey_bit_len/8) bytes to hold the returned private key in Most Significant Byte first order. This buffer may not overlap either xbuf or ybuf.

privkey_bit_lenNumber of bits requested in the private key. Must be in the range (160 <= privkey_bit_len <= 8*k). May be set to DH_FULL_EXPONENT for full range (0 < x < p - 1).

gA pointer to the public generator, length k bytes, Most Significant Byte first.

pA pointer to the public modulus, length k bytes, Most Significant Byte first.

DS51468B-page 54 © 2006 Microchip Technology Inc.

Page 59: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

p_byte_lenThe number of bytes in p, g, pubkey. Must be either 128 or 256. This parameter is equal to the value k mentioned through this section.

xbufA pointer to a working buffer of length 2k. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (64), __section__(".xbss"))) xbuf[2k];

ybufA pointer to a working buffer of length 3k. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[3k];

Remarks: The parameters g,p, p_byte_len may be obtained from the Open SSL C library Diffie-Hellman parameter generation function, or some other trusted external source.MCL_ILLEGAL_SIZE is returned if p_byte_len is neither 128 nor 256. MCL_ILLEGAL_PARAMETER is returned if p does not have its top and bottom bits set, g is not in the range 1<g<p-1, or the pubkey buffer overlaps with the last k bytes of xbuf.

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

File Name: dh.s

Files Needed: dh.o, math.o, mont.o, drbg.o, sha1.o

Clock Cycles: 1024-bit modulus:2320131 for 160-bit private key14653434 for 1024-bit private key

2048-bit modulus:11087206 for 224-bit private key100713682 for 2048-bit private key

Code Example: dh_generate_keys(pubkey, privkey, 160, g, p, 128, xbuf, ybuf);

dh_generate_keys (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 55

Page 60: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

dh_create_shared_keyFunction: Agree on a symmetric key shared with another device.

C Include: dh.h

ASM Include: dh.inc

Prototype: extern unsigned short int dh_create_shared_key(unsigned char *sk, const unsigned char *pubkey_party2, const unsigned char *privkey, unsigned short int privkey_byte_len,const unsigned char *p,unsigned short int p_byte_len,unsigned char *xbuf,unsigned char *ybuf);

Arguments: skA pointer to k bytes to hold the returned shared key in Most Significant Byte first order. This buffer cannot overlap with the last k bytes of xbuf.

pubkey_party2A pointer to the other party’s public key of length k bytes, Most Significant Byte first.

privkeyA pointer to the private key of length privkey_byte_len bytes, Most Significant Byte first.

privkey_byte_lenNumber of bytes in the private key. Must be in the range (20 <= privkey_byte_len <= k).

pA pointer to the public modulus, length k bytes, Most Significant Byte first.

p_byte_lenThe number of bytes in p, sk, pubkey_party2. Must be either 128 or 256. This parameter is equal to the value k mentioned through this section.

xbufA pointer to a working buffer of length 2k. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".xbss"))) xbuf[2k];

ybufA pointer to a working buffer of length 3k. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[3k];

Remarks: The parameters p, p_byte_len may be obtained from the C library Diffie-Hellman parameter generation function, or some other trusted external source.MCL_ILLEGAL_SIZE is returned if p_byte_len is neither 128 nor 256. MCL_ILLEGAL_PARAMETER is returned if p does not have its top and bottom bits set, pubkey_party2 is not in the range 2 to p-2 inclusive, or the pubkey buffer overlaps with the last k bytes of xbuf.

DS51468B-page 56 © 2006 Microchip Technology Inc.

Page 61: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

5.5.2 Digital Signature Algorithm

The following functions are provided for the Digital Signature Algorithm:

• dsa_sign

• dsa_verify

• dsa_generate_keys

Examples of these functions are provided in Appendix B. “Asymmetric Function Examples”.

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

File Name: dh.s

Files Needed: dh.o, math.o, mont.o

Clock Cycles: 1024-bit modulus:2313854 for 160-bit private key4610770 for 1024-bit private key

2048-bit modulus:11076195 for 224-bit private key100606093 for 2048-bit private key

Code Example: dh_create_shared_key(sk, pubkey_party2, privkey, 20, p, 128, xbuf, ybuf);

dsa_signFunction: Compute a DSA signature on a message.

C Include: dsa.h

ASM Include: dsa.inc

Prototype: extern unsigned short int dsa_sign(unsigned char *sig, const unsigned char *hash, const unsigned char *p, const unsigned char *q,const unsigned char *g,const unsigned char *privkey,unsigned char *xbuf,unsigned char *ybuf);

Arguments: sigA pointer to 40 bytes to hold the returned signature components r and s, 20 bytes each in that order with Most Significant Byte first. If buf[0..(n-1)] signifies the first n bytes of a buffer buf, then the sig buffer must not overlap xbuf[20..39] or ybuf[60..79].

hashA pointer to the 20-byte SHA-1 hash of the message with the Most Significant Byte of hash first.

pA pointer to the public field modulus p, length 128 bytes, Most Significant Byte first.

dh_create_shared_key (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 57

Page 62: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

qA pointer to the public subgroup modulus q, length 20 bytes, Most Significant Byte first.

gA pointer to the public field generator g, length 128 bytes, Most Significant Byte first.

privkeyA pointer to the 20-byte private key, Most Significant Byte first.

xbufA pointer to a working buffer of length 276 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (64), __section__(".xbss"))) xbuf[276];

ybufA pointer to a working buffer of length 384 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[384];

Remarks: The parameters p, q and g may be obtained from the Open SSL C library DSA parameter generation function, or some other trusted external source.MCL_ILLEGAL_PARAMETER is returned if any of the following occur: either p or q do not have their top and bottom bits set, if privkey is greater than q-1, or if g is greater than p-1.

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

File Name: dsa.s

Files Needed: dsa.o, math.o, math_mod_inv.o, mont.o

Clock Cycles: 2406817

Code Example: dsa_sign(sig, hash, p, q, g, privkey, xbuf, ybuf);

dsa_sign (Continued)

dsa_verifyFunction: Verify a DSA signature.

C Include: dsa.h

ASM Include: dsa.inc

Prototype: extern unsigned short int dsa_verify(const unsigned char *sig, const unsigned char *hash, const unsigned char *p, const unsigned char *q,const unsigned char *g,const unsigned char *pubkey,unsigned char *xbuf,unsigned char *ybuf);

Arguments: sigA pointer to the alleged signature components r and s, 20 bytes each in that order with Most Significant Byte first.

hashA pointer to the 20-byte SHA-1 hash of the message with the Most Significant Byte of H0 first.

DS51468B-page 58 © 2006 Microchip Technology Inc.

Page 63: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

pA pointer to the public field modulus p, length 128 bytes, Most Significant Byte first.

qA pointer to the public subgroup modulus q, length 20 bytes, Most Significant Byte first.

gA pointer to the public field generator g, length 128 bytes, Most Significant Byte first.

pubkeyA pointer to the 128-byte public key, Most Significant Byte first.

xbufA pointer to a working buffer of length 424 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".xbss"))) xbuf[424];

ybufA pointer to a working buffer of length 384 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[384];

Remarks: MCL_ILLEGAL_PARAMETER is returned if any of the following occur: if either p or q do not have their top and bottom bits set, if pubkey or g is greater than p-1, or if r or s is greater than q-1.

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

File Name: dsa.s

Files Needed: dsa.o, math.o, math_mod_inv.o, mont.o

Clock Cycles: 4548535

Code Example: dsa_sign(sig, hash, p, q, g, privkey, xbuf, ybuf);

dsa_verify (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 59

Page 64: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

dsa_generate_keysFunction: Generate a DSA Public-Private Keypair.

C Include: dsa.h

ASM Include: dsa.inc

Prototype: extern unsigned short int dsa_generate_keys( unsigned char *pubkey, unsigned char *privkey, const unsigned char *p, const unsigned char *q,const unsigned char *g, unsigned char *xbuf, unsigned char *ybuf);

Arguments: pubkeyPointer to 128 bytes of storage to hold the public key, Most Significant Byte first. This buffer may not overlap the last 128 bytes of xbuf.

privkeyPointer to 20 bytes of storage to hold the private key, Most Significant Byte first. This buffer may not overlap either xbuf or ybuf.

pPointer to the public field modulus p, length 128 bytes, Most Significant Byte first.

qPointer to the public subgroup modulus q, length 20 bytes, Most Significant Byte first.

gPointer to the public field generator g, length 128 bytes, Most Significant Byte first.

xbufPointer to a working buffer of length 256 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (64), __section__(".xbss"))) xbuf[256];

ybufPointer to a working buffer of length 384 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[384];

Remarks: MCL_ILLEGAL_PARAMETER is returned if any of the following occur: either p or q do not have their top and bottom bits set, if g is greater than p-1, or if pubkey overlaps the last 128 bytes of xbuf.

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

File Name: dsa.s

Files Needed: dsa.o, math.o, mont.o, drbg.o, sha1.o

Clock Cycles: 2309993

Code Example: dsa_generate_keys(pubkey, privkey, p, q, g, xbuf, ybuf);

DS51468B-page 60 © 2006 Microchip Technology Inc.

Page 65: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

5.5.3 RSA Encryption

The following functions are provided for RSA Encryption/Decryption:

• rsa_encrypt

• rsa_decrypt

Examples of these functions are provided in Appendix B. “Asymmetric Function Examples”.

rsa_encryptFunction: Encrypt a message using RSA.

C Include: rsa_enc_dec.h

ASM Include: rsa_enc_dec.inc

Prototype: extern unsigned short int rsa_encrypt(unsigned char *c, const unsigned char *m, unsigned short int m_byte_len,

const unsigned char *n,unsigned short int n_byte_len,const unsigned char *e,unsigned short int e_byte_len,

unsigned char *xbuf,unsigned char *ybuf);

Arguments: cA pointer to k bytes of storage to hold the ciphertext, Most Significant Byte first. This buffer must not overlap the last k bytes of xbuf.

mA pointer to the plain text message of length m_byte_len. This buffer may overlap the first 128 bytes of xbuf, but not the last 128 bytes.

m_byte_lenThe number of bytes in m such that 0 <= m_byte_len <= k-11.

nA pointer to the public modulus n, Most Significant Byte first.

n_byte_lenThe number of bytes in n, also equal to k used throughout this section. Must be 128 or 256.

eA pointer to the RSA public exponent, Most Significant Byte first. Must correspond to an odd integer.

e_byte_lenThe number of bytes in e such that 0 < e_byte_len <= k.

xbufA pointer to a working buffer of length 2k bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (64), __section__(".xbss"))) xbuf[2k];

ybufA pointer to a working buffer of length 3k bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[3k];

© 2006 Microchip Technology Inc. DS51468B-page 61

Page 66: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

Remarks: In RSA, the public key consists of two values: n and e.MCL_ILLEGAL_SIZE is returned if n_byte_len is neither 128 nor 256, or if m_byte_len is greater than k-11, or if e_byte_len is zero or greater than k.MCL_ILLEGAL_PARAMETER is returned if n does not have its top and bottom bits set, or if e corresponds to an integer that is even, or if the c buffer overlaps with the last k bytes of xbuf.

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

File Name: rsa.s

Files Needed: rsa_enc_dec.o, math.o, mont.o

Clock Cycles: e = 2^16 + 11024-bit modulus:

194608 - 2234422048-bit modulus:

656501 - 715745

Code Example: rsa_encrypt(c, m, m_byte_len, n, n_byte_len, e, e_byte_len, xbuf, ybuf);

rsa_decryptFunction: Decrypt an RSA-encrypted message.

C Include: rsa_enc_dec.h

ASM Include: rsa_enc_dec.inc

Prototype: extern unsigned short int rsa_decrypt(unsigned char *m,

unsigned short int *m_byte_len, const unsigned char *c, unsigned short int c_byte_len,

const unsigned char *privkey,unsigned char *xbuf,unsigned char *ybuf);

Arguments: mPointer to storage to hold the plain text of length pointed to by m_byte_len, with Most Significant Byte first. This buffer may not overlap the first k-11 bytes of xbuf.

m_byte_lenPointer to the number of bytes in m such that 0 <= *m_byte_len <= k-11.

cPointer to the ciphertext c, Most Significant Byte first.

c_byte_lenThe number of bytes in c, also equal to k used throughout this section. Must be 128 or 256.

rsa_encrypt (Continued)

DS51468B-page 62 © 2006 Microchip Technology Inc.

Page 67: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

privkeyPointer to the private key, which consists of five individual values, each of length k/2 bytes. In order, these are:p – a prime factor of the n with Least Significant Byte firstq – another prime factor of n with Least Significant Byte firstdp – the value d (mod p - 1) with Most Significant Byte firstdq – the value d (mod q - 1) with Most Significant Byte firstqinv – the value q-1 (mod p) with Least Significant Byte firstThis buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2))) privkey[5k/2];

xbufA pointer to a working buffer of length 3k/2 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".xbss"))) xbuf[3k/2];

ybufA pointer to a working buffer of length 3k bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[3k/2];

Remarks: MCL_ILLEGAL_SIZE is returned if n_byte_len is neither 128 nor 256.MCL_ILLEGAL_PARAMETER is returned if p or q do not have their top and bottom bits set, or if the m buffer overlaps with the first k-11 bytes of xbuf.MCL_ILLEGAL_CIPHERTEXT is returned if the given ciphertext is not a valid encryption of any message.

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

File Name: rsa.s, rsa_crt.s

Files Needed: rsa_enc_dec.o, rsa_crt.o, math.o, mont.o

Clock Cycles: 1024-bit modulus: 4546989 - 45486682048-bit modulus: 28733014 - 28737501

Code Example: rsa_decrypt(m, m_byte_len, c, c_byte_len, privkey, xbuf, ybuf);

rsa_decrypt (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 63

Page 68: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

5.5.4 RSA Signatures

The following functions are provided for Signing/Verification using the RSA algorithm:

• rsa_sign

• rsa_verify

Examples of these functions are provided in Appendix B. “Asymmetric Function Examples”.

rsa_signFunction: Compute an RSA signature.

C Include: rsa_sign_ver.h

ASM Include: rsa_sign_ver.inc

Prototype: extern unsigned short int rsa_sign(unsigned char *s,

unsigned short int s_byte_len, const unsigned char *h, unsigned short int h_byte_len,

const unsigned char *asn,unsigned short int asn_byte_len, const unsigned char *privkey,

unsigned char *xbuf,unsigned char *ybuf);

Arguments: sPointer to storage to hold the signature of length s_byte_len, with Most Significant Byte first. This buffer may not overlap the first k bytes of xbuf.

s_byte_lenThe number of bytes in s, also equal to k used throughout this section. Must be 128 or 256.

hA pointer to the message hash h, Most Significant Byte first.

h_byte_lenThe number of bytes in h.

asnPointer to the message hash identification data.

asn_byte_lenThe number of bytes in asn.

privkeyPointer to the private key, which consists of five individual values, each of length k/2 bytes. In order, these are:p – a prime factor of the n with Least Significant Byte firstq – another prime factor of n with Least Significant Byte firstdp – the value d (mod p - 1) with Most Significant Byte firstdq – the value d (mod q - 1) with Most Significant Byte firstqinv – the value q-1 (mod p) with Least Significant Byte firstThis buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2))) privkey[5k/2];

xbufPointer to a working buffer of length 3k/2 bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".xbss"))) xbuf[3k/2];

DS51468B-page 64 © 2006 Microchip Technology Inc.

Page 69: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

ybufPointer to a working buffer of length 3k bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[3k/2];

Remarks: The asn and asn_byte_len information may be gotten from the #defined information in rsa_sign_ver.h.MCL_ILLEGAL_SIZE is returned if s_byte_len is neither 128 nor 256, if h_byte_len does not lie in the range 1 to 64 inclusive, or if asn_byte_len does not lie in the range 1 to 19 inclusive.MCL_ILLEGAL_PARAMETER is returned if p and q (inside privkey) do not have their top and bottom bits set, or if the s buffer overlaps with the first k bytes of xbuf.

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

File Name: rsa_sign_ver.s, rsa_crt.s

Files Needed: rsa_sign_ver.o, rsa_crt.o, math.o, mont.o

Clock Cycles: 1024-bit modulus: 45464092048-bit modulus: 28702780

Code Example: rsa_sign(s, s_byte_len, h, h_byte_len, asn, asn_byte_len, privkey, xbuf, ybuf);

rsa_sign (Continued)

rsa_verifyFunction: Verify an RSA signature.

C Include: rsa_sign_ver.h

ASM Include: rsa_sign_ver.inc

Prototype: extern unsigned short int rsa_verify(const unsigned char *s, const unsigned char *h, unsigned short int h_byte_len,

const unsigned char *asn,unsigned short int asn_byte_len,const unsigned char *n,unsigned short int n_byte_len,

const unsigned char *e, unsigned short int e_byte_len,

unsigned char *xbuf,unsigned char *ybuf);

Arguments: sPointer to the RSA signature of length k, Most Significant Byte first.

hPointer to the message hash h, Most Significant Byte first.

h_byte_lenThe number of bytes in h.

asnA pointer to the message hash identification data.

© 2006 Microchip Technology Inc. DS51468B-page 65

Page 70: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

asn_byte_lenThe number of bytes in asn.

nPointer to the public modulus n, Most Significant Byte first.

n_byte_lenThe number of bytes in n, also equal to k used throughout this section. Must be 128 or 256.

ePointer to the RSA public exponent, Most Significant Byte first.

e_byte_lenThe number of bytes in e such that 0 < e_byte_len <= k.

xbufA pointer to a working buffer of length 2k bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".xbss"))) xbuf[2k];

ybufA pointer to a working buffer of length 3k bytes. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (2), __section__(".ybss"))) ybuf[3k];

Remarks: In RSA, the public key consists of two values: n and e.MCL_ILLEGAL_SIZE is returned if n_byte_len is neither 128 or 256, if h_byte_len does not lie in the range 1 to 64 inclusive, if asn_byte_len does not lie in the range 1 to 19 inclusive, or if e_byte_len is zero or greater than k.MCL_ILLEGAL_PARAMETER is returned if n does not have its top and bottom bits set, or the integer corresponding to e is even.

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

File Name: rsa_sign_ver.s

Files Needed: rsa_sign_ver.o, math.o, mont.o

Clock Cycles: e = 2^16 + 11024-bit modulus: 1902482048-bit modulus: 653488

Code Example: rsa_verify(s, h, h_byte_len, asn, asn_byte_len, n, n_byte_len, e, e_byte_len, xbuf, ybuf);

rsa_verify (Continued)

DS51468B-page 66 © 2006 Microchip Technology Inc.

Page 71: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Chapter 6. Hash and Auxiliary Functions

6.1 INTRODUCTION

This chapter describes the hash algorithm-based functions provided in both the dsPIC DSC Symmetric Key and Asymmetric Key Embedded Encryption Libraries. These library functions include the Secure hash Algorithm, SHA-1, Message Digest MD5 and the ANSI X9.82 Deterministic Random Bit Generator function.

6.2 HIGHLIGHTS

This chapter covers the following topics:

• Message Digest/Hash Functions• Auxiliary Functions

6.3 MESSAGE DIGEST/HASH FUNCTIONS

A hash function (also known as a message digest) is a function that produces a cryptographically secure fingerprint of a message. It takes an arbitrary-length message as input and produces a fixed-length, pseudo-random string (the message digest) as output. The message digest has the properties that it is one-way (i.e., given a message it is easy to calculate a digest, but given the digest it is very difficult to find a message that would produce it), and that it is collision-resistant (i.e., it is very difficult to find two messages that produce the same digest). Typically, if two messages differ even in only one bit, the digests of those two messages will differ in about half their bits. In other words, related messages will in general produce entirely uncorrelated digests.

Hash functions play several roles in cryptography:

• They are used to prove knowledge of a secret without revealing that secret. Transmitting a hash of a secret does not reveal the secret (because the hash is one-way) and demonstrates knowledge of that exact secret (because the hash is collision-resistant, so it is extremely unlikely that anyone would know different information that would produce the same hash).

• They are used to process messages before signing. Signing a message involves performing a slow public key operation. By creating a digest of the message and using that as the input to the public key operation, we ensure that we only need one of these slow operations to generate the signature. Additionally, by using the message digest rather than the message itself as the input, we reduce the risk that mathematically related messages have mathematically related signatures (because related messages will produce uncorrelated digests).

• Since their output appears random, they are often used as the core functions within random number generators, such as the X9.82 random number generator provided within this library.

This library provides two hash functions, SHA-1 and MD5.

© 2006 Microchip Technology Inc. DS51468B-page 67

Page 72: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

6.3.1 SHA-1

SHA-1 (the name is derived from the phrase Secure Hash Algorithm) is a US government-approved hash algorithm. It is standardized in the FIPS 180-1 specification, available from: http://www.itl.nist.gov/fipspubs/fip180-1.htm.

The output of SHA-1 is 160 bits long.

6.3.2 MD5

MD5 (the name is derived from the phrase Message Digest) is a widely-used hash algorithm. Its definition can be found, among other places, in RFC 1321, available from: http://www.ietf.org/rfc/rfc1321.txt

The output of MD5 is 128 bits long.

Attacks are known on simplified versions of MD5, though not on the full function. As a result, MD5 is recommended for use only in cases where interoperability is necessary (for example, when implementing the TLS protocol) and not for new or custom cryptographic development.

6.3.3 Function Description

The hash functions described in this section include the following:

• md5

• sha1

For examples of how to use these functions, refer to Appendix C. “Hash and Auxiliary Function Examples”.

md5Function: Hashes data with the MD5 message digest function and, if requested,

produces a 16-byte result.

C Include: md5.h

ASM Include: md5.inc

Prototype: extern unsigned short md5(unsigned char *state, const unsigned char *in,unsigned short in_byte_len, unsigned char flags);

Arguments: stateA pointer to an 88-byte buffer of temporary storage space. When flags includes MD5_FINISH, the first 16 bytes of this will hold the final hash value. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (64))) state[88];

inA pointer to the data to be hashed in this call.

in_byte_lenThe number of bytes of data in in.

flagsThe value of flags can be any combination of the following values (defined in md5.h):

MD5_INIT Initialize stateMD5_DATA_ONLY Add input dataMD5_FINISH Finish computation

DS51468B-page 68 © 2006 Microchip Technology Inc.

Page 73: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

.

Remarks: This function can be called one or more times in the computation of a single hash value. Calling with the MD5_INIT flag resets the initial state. This must be performed at the beginning of the computation of any new hash value. Calling with the MD5_DATA_ONLY flag processes additional data. This may be called zero or more times until all input data has been processed. Calling with MD5_FINISH completes processing the input data, finalizes the hash value and stores the result in the first 16 bytes of state.

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

File Name: md5.s

Files Needed: md5.o

Clock Cycles: (2858 * no. of blocks) + 166

Code Example: md5(state, in, 20, MD5_INIT);md5(state, in, 45, MD5_DATA_ONLY);md5(state, in, 20, MD5_FINISH);

sha1Function: Hashes data with the SHA-1 message digest function and, if requested,

produces a 20-byte result.

C Include: sha1.h

ASM Include: sha1.inc

Prototype: extern unsigned short sha1( unsigned char *state, const unsigned char *in, unsigned short in_byte_len, unsigned char flags);

Arguments: stateA pointer to a 92-byte buffer of temporary storage space. When flags includes SHA1_FINISH, the first 16 bytes of this will hold the final hash value. This buffer must be allocated as follows:unsigned char __attribute__ ((aligned (64), __section__(".xbss") )) state[92];

inA pointer to the data to be hashed in this call.

in_byte_lenThe number of bytes of data in in.

flagsThe value of flags can be any combination of the following values (defined in sha1.h):

SHA1_INIT Initialize stateSHA1_DATA_ONLY Add input dataSHA1_FINISH Finish computation

md5 (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 69

Page 74: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

6.4 AUXILIARY FUNCTIONS

This library includes the ANSI X9.82 pseudo-random number generator function to generate cryptographically random byte strings. X9.82 is defined in the draft ANSI X9 standard, available to members of the X9 organization at: http://www.x9.org.

This is also known as a deterministic random bit generator (DRBG). A pseudo-random number generator is an algorithm that expands an unknown seed string into an arbitrary-length, statistically random output. A cryptographically secure pseudo-random number generator has the property that any attacker who does not know the seed will not be able to predict the next bit of output from the generator, no matter how many previous bits of output he knows.

The security of the pseudo-random number generator depends on the seed being unguessable by an adversary. It must be based on data that an attacker could not observe and that is drawn from a large sample space. Where to obtain this seed data is out of the scope of this manual, but typically it may be based on taking a large number of measurements of time-sensitive system information.

6.4.1 Random Number Generation Functions

This section describes the properties of the following Random Number Generation functions.

• drbg_seed

• drbg_generate

• drbg_reseed

For examples of how these function are used, see Appendix C. “Hash and Auxiliary Function Examples”.

Remarks: This function can be called one or more times in the computation of a single hash value. Calling with the SHA1_INIT flag resets the initial state. This must be performed at the beginning of the computation of any new hash value. Calling with the SHA1_DATA_ONLY flag processes additional data. This may be called zero or more times until all input data has been processed. Calling with SHA1_FINISH completes processing the input data, finalizes the hash value and stores the result in the first 20 bytes of state.

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

File Name: sha1.s

Files Needed: sha1.o

Clock Cycles: (4427 * no. of blocks) + 306

Code Example: sha1(state, in, 0, SHA1_INIT);sha1(state, in, 45, SHA1_DATA_ONLY);sha1(state, in, 0, SHA1_FINISH);

sha1 (Continued)

DS51468B-page 70 © 2006 Microchip Technology Inc.

Page 75: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

drbg_seedFunction: Sets the initial seed value for Deterministic Random Bit Generator from

ANSI X9.82 draft which generates a string of pseudorandom bytes using the related drbg_generate and drbg_reseed functions. The length of the seed must be 20 bytes.

C Include: drbg.h

ASM Include: drbg.inc

Prototype: extern unsigned short drbg_seed(unsigned char *workbuf, const unsigned char *seed);

Arguments: workbufA pointer to a 92-byte buffer of temporary storage space for this function. This buffer must be allocated as follows:unsigned char __attribute__ * ((aligned (64), __section__(".xbss") )) workbuf[92];

seedA pointer to a buffer that holds the seed, which should be a truly-random string and not generated from a pseudo-random source like rand(). The length of this buffer must be 20 bytes.

Remarks: DRBG maintains an internal state of 40 bytes between calls to the generator. This state is saved in storage allocated internally to the library. Therefore, only one instance of this function may be invoked. This function should be called before the drbg_generate function. Subsequent calls to this function will re-initialize the internal state with the provided seed.

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

File Name: drbg.s

Files Needed: drbg.o

Clock Cycles: 4914

Code Example: drbg_seed(workbuf, seed);

drbg_generateFunction: Deterministic Random Bit Generator from ANSI X9.82 draft standard

generates a string of pseudorandom bytes from a seed provided in the related drbg_seed and drbg_reseed functions. The length of the string of bytes is user-defined in the range 1 to 65,535 inclusive.

C Include: drbg.h

ASM Include: drbg.inc

Prototype: extern unsigned short drbg_generate(unsigned char *workbuf, unsigned char *out, unsigned short out_byte_len);

© 2006 Microchip Technology Inc. DS51468B-page 71

Page 76: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

Arguments: workbufA pointer to a 92-byte buffer of temporary storage space for this function. This buffer must be allocated as follows:unsigned char __attribute__ * ((aligned (64), __section__(".xbss") )) workbuf[92];

outA pointer to a buffer to hold this function’s output. The length of this buffer must be greater than or equal to the number of bytes requested in the out_byte_len parameter.

out_byte_lenThe number of bytes to be returned in the out buffer. This number must be in the range 1 to 65,535 inclusive.

Remarks: DRBG maintains an internal state of 40 bytes between calls to the generator. This state is saved in storage allocated internally to the library. Therefore, only one instance of this function may be invoked. This function should only be called after the internal state has been initialized in a call to the drbg_seed function. If this condition is not met a error code of MCL_DRBG_NOT_INITIALIZED is returned.An error code of MCL_ILLEGAL_SIZE is returned if out_byte_len is zero.

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

File Name: drbg.s

Files Needed: drbg.o

Clock Cycles: (4789 * no. of 20-byte blocks) + 142

Code Example: drbg_generate(workbuf, out, 20);

drbg_reseedFunction: Adds additional randomness to the internal state of the Deterministic

Random Bit Generator from ANSI X9.82 draft which generates a string of pseudorandom bytes using the related drbg_generate and drbg_seed functions.

C Include: drbg.h

ASM Include: drbg.inc

Prototype: extern unsigned short drbg_reseed(unsigned char *workbuf, const unsigned char *seed);

drbg_generate (Continued)

DS51468B-page 72 © 2006 Microchip Technology Inc.

Page 77: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

Arguments: workbufA pointer to a 92-byte buffer of temporary storage space for this function. This buffer must be allocated as follows:unsigned char __attribute__ * ((aligned (64), __section__(".xbss") )) workbuf[92];

seedA pointer to a buffer that holds the additional randomness, which should be a truly-random string and not generated from a pseudo-random source like rand(). The length of this buffer must be 20 bytes.

Remarks: DRBG maintains an internal state of 40 bytes between calls to the generator. This state is saved in storage allocated internally to the library. Therefore, only one instance of this function may be invoked. Calling this function will combine the internal state with the seed provided to update the internal state. If there is no existing state, i.e., drbg_seed has not been called, then an error code of MCL_DRBG_NOT_INITIALIZED is returned.

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

File Name: drbg.s

Files Needed: drbg.o

Clock Cycles: 9898

Code Example: drbg_reseed(workbuf, seed);

drbg_reseed (Continued)

© 2006 Microchip Technology Inc. DS51468B-page 73

Page 78: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

NOTES:

DS51468B-page 74 © 2006 Microchip Technology Inc.

Page 79: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Appendix A. Symmetric Function Examples

A.1 INTRODUCTION

This appendix contains examples of the symmetric encryption functions included in the dsPIC30F Symmetric Key Embedded Encryption Library.

A.2 HIGHLIGHTS

Included are the following:

• AES-ECB Example• AES-CBC Example• AES-CBC-MAC Example• AES-CTR Example• AES-CCM Example• TDES-ECB Example• TDES-CBC Example• TDES-CBC-MAC Example• TDES-CTR Example

A.3 SYMMETRIC FUNCTION EXAMPLES

A.3.1 AES-ECB Example

#include <stdio.h>#include "ret_codes.h"#include "aes_encrypt.h"#include "aes_decrypt.h"#include "aes_ecb.h"

/* AES permutes 128 bits to 128 bits with a 128-bit key. Here is a plaintext example */

unsigned char plaintext[]={0x17, 0x38, 0xFA, 0xC9, 0x04, 0xD2, 0x62, 0x7C,0x11, 0x6A, 0xCD, 0xB4, 0xAF, 0xC0, 0x42, 0x82,

};

© 2006 Microchip Technology Inc. DS51468B-page 75

Page 80: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* and this is what the corresponding ciphertext should be: */

unsigned char ciphertext[]={0x75, 0xbe, 0x1b, 0xab, 0x84, 0xd1, 0xf0, 0x1a, 0x81, 0xa1, 0x12, 0x7f, 0xd0, 0xbb, 0x29, 0x3a,

};

/* When AES is used with this key */

const unsigned char key[] ={0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6,0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF,};

/* Before performing an aes encryption, you should convert the key into a format that is particularly efficient for the encryption algorithm - so called encryption "round keys". This process of transforming a key into its encryption round keys, is called key-scheduling and uses the function aes_encrypt_key_sched. */

/* For aes_encrypt you need a buffer of 44 long ints (176 bytes) in which to store the encryption round keys */

unsigned long int enc_round_keys[44];

/* Similarly, before performing an AES decryption, you must produce decryption round keys. These round keys are not the same as the AES encryption round keys. They require a different buffer, also of size 44 long ints (176 bytes). */

unsigned long int dec_round_keys[44];

/* Note: Key scheduling varies extensively for different underlying ciphers. With AES, the only way to produce decryption round keysis from the encryption round keys. Even if you do not want to encrypt any data with the key, you must follow this route:

aes key -> encryption round keys -> decryption round keys, where the first transformation uses aes_encrypt_key_sched() and the second transformation uses aes_decrypt_key_sched(). */

int main(void) {unsigned char ans[16];int i;int retcode;

/* Perform AES ECB encryption: First, calculate the encryption round keys */

if ((retcode = aes_encrypt_key_sched(enc_round_keys, key)) !=MCL_SUCCESS){

printf("Problem producing the AES encrypton round keys!\n");return 1;}

/* Next encrypt 16 bytes (i.e. one block) using AES, returning the ciphertext in the ans buffer (also of length 16 bytes) */

if ((retcode = aes_ecb_encrypt(ans, plaintext,16,(const unsigned long int *) enc_round_keys)) !=

MCL_SUCCESS) {printf("Problem performing AES ECB encryption!\n");

DS51468B-page 76 © 2006 Microchip Technology Inc.

Page 81: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

return 2;}

/* Perform AES ECB decryption: First, calculate decryption round keys */

/* Reminder: Key scheduling varies extensively for different underlying ciphers. With AES, the only way to produce the decryption round keys is from the encryption round keys. Even if you do not want to encrypt any data with the key, you must follow this route:

aes key -> encryption round keys -> decryption round keys, where the first transformation uses aes_encrypt_key_sched and the second transformation uses aes_decrypt_key_sched. */

/* In this case the encryption round keys are already computed, so you can use them to compute the decryption round keys */

if ((retcode = aes_decrypt_key_sched(dec_round_keys,(const unsigned long int *) enc_round_keys)) !=

MCL_SUCCESS) {printf("Problem producing the AES decryption round keys!\n");return 3;}

/* Decrypt 16 bytes (i.e. one block) using AES, returning the plaintext in the ans buffer (also of length 16 bytes) */

if ((retcode = aes_ecb_decrypt(ans, ciphertext,16,const unsigned long int *) dec_round_keys)) !=

MCL_SUCCESS) {printf("Problem performing the AES ECB decryption!\n");return 4;}

/* The number of bytes for AES ECB mode must be multiple of 16 (i.e. ECB mode only works for full blocks of encrypted data */

if ((retcode = aes_ecb_decrypt(ans, ciphertext, 15,(const unsigned long int *) dec_round_keys)) !=

MCL_ILLEGAL_SIZE) {printf("AES ECB mode only works when the ");printf("number of bytes is a multiple of 16!\n");return 5;}

/* You can encrypt and decrypt more blocks with the ECB mode of operation. For example if aes_ecb_encrypt has a third argument of 160, the first 16 bytes of the plaintext will be AES encrypted with the round keys given, and the output are written to the first 16 bytes of the ciphertext buffer. The next 16 bytes of plaintext are encrypted with the same round keys and stored in the next 16 bytes of ciphertext ciphertext, and so on, until all 160 bytes (i.e. 10 blocks) have been processed. This mode of operation is NOT recommended for general purpose cryptographic encryption of long blocks of data. */

printf("Example code finished successfully!\n");return 0; }

© 2006 Microchip Technology Inc. DS51468B-page 77

Page 82: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

A.3.2 AES-CBC Example

#include <stdio.h>#include "ret_codes.h"#include "aes_encrypt.h"#include "aes_decrypt.h"#include "aes_cbc_encrypt_and_mac.h"#include "aes_cbc_decrypt.h"

const unsigned char cbc_aes_key[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,

};

const unsigned char cbc_iv[] = {0xa6, 0x7a, 0x28, 0x1f, 0xea, 0x98, 0x77, 0x15,0x27, 0xf7, 0x19, 0x8a, 0xa7, 0x2b, 0x41, 0x56,

};

const unsigned char cbc_iv2[] = {0xf7, 0x11, 0x9a, 0x2f, 0x84, 0x17, 0xf7, 0x06,0x9a, 0x81, 0x6c, 0xc2, 0x13, 0x52, 0x8a, 0xfd,

};

const unsigned char cbc_pt[] = {0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20,0x66, 0x6f, 0x72, 0x20, 0x61, 0x6c, 0x6c, 0x20,0x15, 0x3b, 0xd3, 0x19, 0x34, 0xe6, 0x51, 0x76,0xcb, 0x65, 0xc1, 0xf7, 0xe3, 0x5d, 0xf3, 0x24,0x66, 0x3f, 0x9b, 0x17, 0xc4, 0x91, 0x97, 0x10,

};

const unsigned char cbc_ct[] = {0x68, 0x41, 0x30, 0x29, 0x47, 0x4c, 0x39, 0x8a, 0xc1, 0xed, 0xf3, 0xbe, 0xd7, 0x72, 0x6d, 0x4a,0x5d, 0xe9, 0x82, 0x67, 0x45, 0x35, 0x61, 0xf4, 0xd5, 0xeb, 0xc6, 0xff, 0x05, 0xdd, 0xc5, 0xf0,0x24, 0xaa, 0xed, 0x85, 0x04, 0xee, 0x05, 0x90, 0xdc, 0x96, 0xb1, 0x99, 0x77, 0xb6, 0x6c, 0xe9,

};

const unsigned char cbc_ct2[] = {0x98, 0xa9, 0x9b, 0x95, 0xd3, 0xa4, 0xf4, 0xa4, 0x60, 0x97, 0x74, 0x61, 0x14, 0x3d, 0x8e, 0x82, 0xb5, 0x41, 0xdc, 0xf4, 0x51, 0xf7, 0xf3, 0xef, 0x40, 0xd3 0xae, 0x2d, 0x11, 0xa3, 0x72, 0x22, 0x70, 0xf8, 0x76, 0xb1, 0x5a, 0xe1, 0x67, 0xf0, 0x17, 0x9c, 0x5b, 0xda, 0x5e, 0xb8, 0x78, 0xeb,

};

unsigned long int enc_round_keys[44];unsigned long int dec_round_keys[44];unsigned char __attribute__ ((aligned (2))) state[34];

/********************************************************************/intmain(void) {

unsigned char ans[48];unsigned char ans2[48];

DS51468B-page 78 © 2006 Microchip Technology Inc.

Page 83: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

short int retcode, out_byte_len, total_out;int i, j;int good_op;

/* AES CBC encryption is a chaining mode of encryption which xors the ciphertext of the previous block on to the current /* plaintext before performing a standard aes encryption. The /* first plaintext block is xor'ed with an initial value (IV). */

/* To perform a AES CBC encryption you must first obtain AES encryption round keys

if ((retcode = aes_encrypt_key_sched(enc_round_keys, cbc_aes_key))!=MCL_SUCCESS){

printf("Problem producing round keys!\n");return 1;

}

/* The AES_INIT flag must be set when starting the chaining mode, and the AES_FINISH flag must be set when ending the chaining mode. When the whole buffer is being processed they may be used together. When you supply plaintext that is neither at the start or end, you can use the AES_DATA_ONLY flag as shown below. The number of inputbytes must be a multiple of 16, except when internal padding is being used and it is the last block (designated by setting the AES_FINISH and AES_INTERAL_PAD flags).*/

/* Encryption Example 1 Not using internal padding */

/* Before starting the chaining mode, make sure the IV resides in the first 16 bytes of the state */

for (i = 0; i < 16; i++) state[i] = cbc_iv[i];good_op = 1;

/* Then call aes_cbc_encrypt with the AES_INIT flag set, which processes the IV and any input bytes given to it (in this example the first 16 bytes of plaintext). */

retcode = aes_cbc_encrypt( state, ans, &out_byte_len, cbc_pt, 16,enc_round_keys, AES_INIT);

/* In normal usage the out_byte_length will be the same as the input byte length */

good_op &= (out_byte_len == 16);

/* You then encrypt the next 16 bytes of the plaintext */

retcode|= aes_cbc_encrypt(state, ans+16, &out_byte_len, cbc_pt+16, 16,enc_round_keys, AES_DATA_ONLY);

/* Check that the correct number of bytes was processed. */

good_op &= (out_byte_len == 16);

© 2006 Microchip Technology Inc. DS51468B-page 79

Page 84: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* Finally, you encrypt the last 16 bytes of the plaintext. The last block of plaintext must be signalled by setting the AES_FINISH flag */

retcode |= aes_cbc_encrypt(state, ans+32, &out_byte_len, cbc_pt+32, 16,enc_round_keys, AES_FINISH);

good_op &= (out_byte_len == 16);

/* and perform the necessary checks and error reports */

if (retcode != MCL_SUCCESS || !good_op) {printf("Problem with aes_cbc_encrypt!\n");return 2;}

/* Encryption Example 2 (with the same key as example 1) Using internal padding */

/* As mentioned above, in normal use the plaintext byte length must be a multiple of 16 so that whole blocks can be processed. If the AES_INTERNAL_PAD flag is set, the last block padded is padded with PKCS #5 padding, which allows for handling of arbitrary byte-length data. This means the ciphertext length may be longer than the plaintext, and for this reason the length of the buffer is returned to the calling function. Note that if the last block is a full 16 bytes, then PKCS #5 padding results in the encryption of an extra block. */

/* Initialize the start of state with a different IV */

for (i = 0; i < 16; i++) state[i] = cbc_iv2[i];good_op = 1;

/* Encrypt just 44 bytes of the plaintext; first 16 bytes, and then 28 bytes. */

/* All but the last call to aes_cbc_encrypt must have whole blocks of input data (i.e. byte length a multiple of 16. */

retcode = aes_cbc_encrypt(state, ans2, &out_byte_len, cbc_pt, 16, (const unsigned long int *) enc_round_keys, AES_INIT );good_op &= (out_byte_len == 16);

/* The AES_INTERNAL_PAD flag need only be set on the last call, i.e., when AES_FINISH is also set. */

retcode|=aes_cbc_encrypt(state, ans2+16, &out_byte_len, cbc_pt+16, 28,(const unsigned long int *) enc_round_keys,AES_FINISH | AES_INTERNAL_PAD);

/* The number of output bytes will always be a multiple of 16. */

good_op &= (out_byte_len == 32);if (retcode != MCL_SUCCESS || !good_op) {

printf("Problem with aes_cbc_encrypt!\n");return 3;}

DS51468B-page 80 © 2006 Microchip Technology Inc.

Page 85: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* Decryption Example 1 Not using internal padding */

/* An AES CBC decryption uses the AES decryption function, so you must first obtain the corresponding decryption keys */

retcode = aes_decrypt_key_sched(dec_round_keys,(const unsigned long int *) enc_round_keys);if (retcode != MCL_SUCCESS) {printf("Problem producing round keys!\n");return 4;}

/* Before starting the chaining mode, make sure the IV resides in the first 16 bytes of the state */

for (i = 0; i < 16; i++) state[i] = cbc_iv[i];

/* The AES_INIT, AES_DATA_ONLY and AES_FINISH flags work the the same way in decryption as they do in encryption (see above).The input data length for CBC decryption must always be a multiple of 16 bytes, whether internal padding is used and whether it is the last block. Below you will decrypt the data with two calls to aes_cbc_decrypt,rather than the three used to encrypt the data. */

good_op = 1;

/* The first call should have AES_INIT set */

retcode = aes_cbc_decrypt(state, ans, &out_byte_len, cbc_ct, 32,(const unsigned long int *) dec_round_keys, AES_INIT);

/* Check that the correct number of bytes was processed */

good_op &= (out_byte_len == 32);

/* The last call should have AES_FINISH set */

retcode |= aes_cbc_decrypt(state, ans+32, &out_byte_len, cbc_ct+32, 16,(const unsigned long int *) dec_round_keys, AES_FINISH);

/* Check that the correct number of bytes was processed */

good_op &= (out_byte_len == 16);

if (retcode != MCL_SUCCESS || !good_op) {printf("Problem with aes_cbc_decrypt!\n");return 5;}

/* Decryption Example 2 (with same key as example 1) Using internal padding */

/* Initialize the state with the correct IV */

for (i = 0; i < 16; i++) state[i] = cbc_iv2[i];good_op = 1;

© 2006 Microchip Technology Inc. DS51468B-page 81

Page 86: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* and choose to decrypt all the data at once */

retcode = aes_cbc_decrypt(state, ans2, &out_byte_len, cbc_ct2, 48, (const unsigned long int *) dec_round_keys, AES_INIT | AES_FINISH | AES_INTERNAL_PAD);

/* When internal padding is set, it will be stripped, and out_byte_len will hold the number of bytes of the original plaintext. If the padding is found to be incorrect.the aes_cbc_decrypt function returns an MCL_ILLEGAL_PADDINGerror return code, and any remaining plaintext is not output.*/

good_op &= (out_byte_len == 44);if (retcode != MCL_SUCCESS || !good_op) {

printf("Problem with aes_cbc_decrypt!\n");return 6;}

/* Common mistakes: Forgetting that aes_decrypt_key_sched takes the encryptionround keys as inputIf aes_cbc_encrypt or aes_cbc_decrypt fails, it returns a MCL_ILLEGAL_SIZE value. Some possible mistakes with AES CBCinclude: */

retcode = aes_cbc_encrypt(state, ans, &out_byte_len, cbc_pt, 0,(const unsigned long int *) enc_round_keys,AES_INIT | AES_FINISH);

if (retcode != MCL_ILLEGAL_SIZE) {printf("This should fail because some data must be processed!\n");return 7;}

retcode = aes_cbc_encrypt(state, ans, &out_byte_len, cbc_pt, 7,(const unsigned long int *) enc_round_keys,AES_INIT | AES_FINISH);

if (retcode != MCL_ILLEGAL_SIZE) {printf("This should fail... not an integral number of blocks!\n");return 8;}

printf("Example code finished successfully!\n");return 0;}

DS51468B-page 82 © 2006 Microchip Technology Inc.

Page 87: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

A.3.3 AES-CBC-MAC Example

#include <stdio.h>#include "ret_codes.h"#include "aes_encrypt.h"#include "aes_cbc_encrypt_and_mac.h"

const unsigned char aes_key[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,

};

const unsigned char message[] = {0xac, 0x34, 0x01, 0xa3, 0x7e, 0x23, 0xf9, 0x34,0x33, 0x26, 0x5e, 0x1d, 0x53, 0xe2, 0x99, 0x57,0xdf, 0x22, 0xf4, 0x98, 0x35, 0xee, 0x65, 0xa7,0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20,0x66,

};

const unsigned char mac[] = {0x29, 0xeb, 0xf4, 0xe6, 0xf1, 0xcd, 0x4b, 0x65, 0x29, 0xbb, 0xe1, 0x5d, 0x3c, 0xa6, 0xa9, 0xfb,

};

unsigned long int enc_round_keys[44];unsigned char __attribute__ ((aligned (2))) state[34];

/********************************************************************/intmain(void) {

unsigned char ans[16];short int retcode, out_byte_len, total_out;int i, j;

/* AES CBC MAC is a chaining mode of authentication which xorsthe message data from the previous block on to the currentmessage block before performing a standard aes encryption.The output of the final block is the authentication value(MAC). The first message block is not xor'ed with anything. */

/* AES CBC MAC makes use of AES encryption, so you must first

obtain AES encryption round keys */

retcode = aes_encrypt_key_sched(enc_round_keys, aes_key);if (retcode != MCL_SUCCESS) {

printf("Problem producing encryption round keys!\n");return 1;

}

/* The AES_INIT flag must be set when starting the chaining mode,and the AES_FINISH flag must be set when ending the chainingmode. When the whole buffer is being processed they may be usedtogether. When supplying message data that is neither atthe start or end, then one may use the AES_DATA_ONLY flag asbelow. */

© 2006 Microchip Technology Inc. DS51468B-page 83

Page 88: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* aes_cbc_mac accepts any number of bytes < 65536 as input,i.e. the number of input bytes is not restricted to be a blocklength. Internally the function buffers any partial-blockdata. If there is a partial block of data left over at the end(i.e. when AES_FINISH is set), then this block is expanded toa full block by appending zeros, before performing the xor'ingand aes encryption stages to produce the MAC. */

/* We start the mac by setting AES_INIT, and processing any giveninput bytes (in this case 13) */

if ((retcode = aes_cbc_mac(state, NULL, message, 13,enc_round_keys, AES_INIT)) != MCL_SUCCESS){

printf("There was a problem performing the aes cbc mac!\n");return 2;

}

/* For any data that needs to be input before the last chunk weset the AES_DATA_ONLY flag */

if ((retcode = aes_cbc_mac(state, NULL, message+13, 17,enc_round_keys, AES_DATA_ONLY)) != MCL_SUCCESS){

printf("Problem performing the aes cbc mac!\n");return 3;

}

/* When the last chunk of data is given we must set theAES_FINISH flag, and give a buffer in which to store the 16byte MAC result. */

if ((retcode = aes_cbc_mac(state, ans, message+30, 11,enc_round_keys, AES_FINISH)) != MCL_SUCCESS){

printf("There was a problem performing the aes cbc mac!\n");return 4;

}

printf("Example code finished successfully!\n");return 0;

}

DS51468B-page 84 © 2006 Microchip Technology Inc.

Page 89: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

A.3.4 AES-CTR Example

#include <stdio.h>#include "ret_codes.h"#include "aes_encrypt.h"#include "aes_ctr.h"

/* An aes key to be used in counter mode */

const unsigned char aes_key[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,

};

/* An IV for counter mode */

const unsigned char aes_ctr_iv[] = {0x87, 0xf2, 0x7a, 0xe5, 0x11, 0x97, 0x2e, 0xd4,0x29, 0x17, 0x81, 0xa2, 0x3e, 0x11, 0xf3, 0xee,

};

/* Some plaintext */

const unsigned char aes_ctr_pt[] = {0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20,0x66, 0x6f, 0x72, 0x20, 0x61, 0x6c, 0x6c, 0x20,0x15, 0x3b, 0xd3, 0x19, 0x34, 0xe6, 0x51, 0x76,0xcb, 0x65, 0xc1, 0xf7, 0xe3, 0x5d, 0xf3, 0x24,0x66,

};

/* the ciphertext corresponding to the above plaintext, IV and key */

const unsigned char aes_ctr_ct[] = {0x68, 0x1e, 0xc4, 0x2f, 0xa6, 0xd5, 0xda, 0x2d, 0x40, 0xd6, 0x71, 0x71, 0x54, 0xa6, 0x70, 0x81, 0x55, 0x32, 0x56, 0x8c, 0x99, 0xb2, 0xfa, 0xad, 0x41, 0x6e, 0xff, 0x3e, 0xd0, 0x15, 0xf8, 0x51, 0x63, 0x18, 0xbd, 0x61, 0xa7, 0xc5, 0x86, 0x94, 0x97,

};

unsigned long int enc_round_keys[44];unsigned char __attribute__ ((aligned (2))) state[34];

/********************************************************************/intmain(void) {

unsigned char ans[41];short int retcode, out_byte_len, total_out;int i, j;

/* AES CTR CRYPT can be used for both encryption anddecryption. It uses the AES encryption function to make astream of pseudorandom bytes which are xor'ed to the plaintextto create the ciphertext in encryption. In decryption the samepseudorandom bytes are xor'ed to the ciphertext to retrieve theoriginal plaintext. The stream of pseudorandom bytes isobtained by aes encrypting an initial value (IV) to obtain the

© 2006 Microchip Technology Inc. DS51468B-page 85

Page 90: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

first 16 pseudorandom bytes, and then incrementing the IV andaes encrypting to obtain the next 16 pseudorandom bytes, andthen carrying on incrementing and encrypting in this fashion(this is the basis for the name counter (ctr) mode). */

/* AES CTR CRYPT makes use of AES encryption, so one must firstobtain AES encryption round keys */

if ((retcode = aes_encrypt_key_sched(enc_round_keys, aes_key))!= MCL_SUCCESS) {

printf("Problem producing round keys!\n"); return 1;

}

/* The AES_INIT flag must be set when starting the counter mode,and the AES_FINISH flag must be set when ending the countermode. When the whole buffer is being processed they may be usedtogether. When supplying message data that is neither atthe start or end, then one may use the AES_DATA_ONLY flag asbelow. */

/* The IV must be placed in the first 16 bytes of the statebuffer before any calls to aes_ctr_crypt */

for (i = 0; i < 16; i++) state[i] = aes_ctr_iv[i];

/* Then call aes_ctr_crypt with the AES_INIT set, andprocess any input bytes (13 in this case). The function outputsexactly as many bytes as were input. */

if ((retcode = aes_ctr_crypt(state, ans, aes_ctr_pt, 13,enc_round_keys, AES_INIT)) != MCL_SUCCESS){

printf("Problem performing the aes ctr encryption!\n");return 2;

}

/* For any data that needs to be input before the last chunk weset the AES_DATA_ONLY flag */

if ((retcode = aes_ctr_crypt(state, ans+13, aes_ctr_pt+13, 17,enc_round_keys, AES_DATA_ONLY)) != MCL_SUCCESS){

printf("Problem performing the aes ctr encryption!\n");return 3;

}

/* When the last chunk of data is given we must set theAES_FINISH flag */

if ((retcode = aes_ctr_crypt(state, ans+30, aes_ctr_pt+30, 11,enc_round_keys, AES_FINISH)) != MCL_SUCCESS){

printf("Problem performing the aes ctr encryption!\n");return 4;

}

/* Decryption works in exactly the same way. It also uses the AESencryption function (to produce the pseudorandom keystream), soreuse the same round keys as above */

/* First set the IV */

DS51468B-page 86 © 2006 Microchip Technology Inc.

Page 91: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

for (i = 0; i < 16; i++) state[i] = aes_ctr_iv[i];

/* and then we call aes_ctr_crypt (this time we've chosen toprocess the whole buffer in one go) */

if ((retcode = aes_ctr_crypt(state, ans, aes_ctr_ct, 41,enc_round_keys, AES_INIT | AES_FINISH))!= MCL_SUCCESS){

printf("Problem performing the aes ctr decryption!\n");return 5;

}

printf("Example code finished successfully!\n");return 0;

}

© 2006 Microchip Technology Inc. DS51468B-page 87

Page 92: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

A.3.5 AES-CCM Example

#include <stdio.h>#include "ret_codes.h"#include "aes_encrypt.h"#include "aes_ccm.h"

/* If you want to encrypt and authenticate data using aes_ccmthen there are three important buffers:1) the AD_buffer: corresponds only to data to be authenticated 2) the AED_buffer: corresponds to data to be both authenticated

and encryted3) the mac buffer: at most 16 bytes to hold authentication data */

const unsigned char ccm_AD[]={0xc4, 0xb8, 0x74, 0x8b, 0xf9, 0x2f, 0x39, 0xde,0x85, 0xd4, 0xe2, 0x08, 0xf5, 0x1d, 0x6f, 0x19,0x1b, 0xfc, 0xb9, 0xd7, 0x5b, 0x6c, 0xb9, 0xd9,0x64, 0x49, 0x1c, 0x1c, 0x37, 0x27, 0xf4, 0x0f,0x67, 0x22, 0xf6, 0xe3, 0xbf, 0x58, 0x66, 0x95,0x78, 0x12, 0x11, 0x2f, 0xe9, 0x82, 0x36, 0x54,0xf2, 0x98, 0xc6, 0x99, 0x45, 0xad,

};

const unsigned char ccm_AED[]={0x7a, 0x15, 0x5f, 0xbf, 0x43, 0x87, 0xe5, 0x41,0xcb, 0x78, 0x1d, 0x57, 0xe1, 0x2b, 0x44, 0x85,0x2f, 0x63, 0x28, 0x7e, 0x94, 0x32, 0x8d, 0xb1,0x35, 0x99, 0x8f, 0xcd, 0x52, 0xc9, 0xbb, 0xb2,0x9d, 0x53, 0xa5, 0x18, 0xf6, 0xb2, 0x6d, 0x07,0x38,

};

unsigned char ccm_mac[16];

/* The CCM standard allows the lengths of the first two buffers to beas large as 2^64, so these lengths cannot be stored as short orlong ints. Instead they are represented as arrays of 8-bit wordsin network byte order. */

/* For example the following might be how one specifies a buffer of length 0x28217 = 1643750 */

/* short int length_of_AD_length = 3; unsigned char length_of_AD[] = {0x02, 0x82, 0x17}; */

/* Clearly such large buffers cannot be stored and accessed at onetime, so the library allows for the buffers to be processed insmaller chunks. */

/* The minimum buffer size to hold the length of AED is 2 bytes

For small buffers you may need to set the first few bytes inthe length buffer to zero, e.g. */

short int length_of_AED_length = 4;unsigned char AED_length[] = {0x0, 0x0, 0x0, 0x29};

DS51468B-page 88 © 2006 Microchip Technology Inc.

Page 93: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* The maximum size of the AED_length buffer is 8 bytes */

/* The nonce buffer concatenated with the buffer holding the length of AED should equal 15 bytes. */

short int nonce_length=11;

unsigned char nonce[]={0x0e, 0x55, 0xf0, 0x2b, 0xe2, 0x4f, 0xd3, 0x59,0xb0, 0xb2, 0xde,

};

/* Size of the AD_length buffer can be between 1-8 bytes inclusive */

short int length_of_AD_length = 1;unsigned char AD_length[] = {0x36};

/* The length of the mac must be 4, 6, 8, 10, 12, 14, or 16 bytes */

short int length_of_mac = 8;

/* CCM uses ONLY AES ENCRYPTION round keys (for authentication,encryption, decryption, and verification) */

const unsigned char aes_key[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c,

};

unsigned long int enc_round_keys[44];

/* CCM needs a state buffer aligned in the following way */

unsigned char __attribute__ ((aligned (2))) state[92];

/********************************************************************/intmain(void) {

unsigned char ans_ct[80], ans_pt[80];short int retcode, out_byte_len, total_out;int i;

/* CCM uses ONLY aes ENCRYPTION round keys (for authentication,encryption, decryption and verification) */

if ((retcode = aes_encrypt_key_sched(enc_round_keys, aes_key))!= MCL_SUCCESS){

printf("There was a problem obtaining the round keys!\n");return 1;

}

© 2006 Microchip Technology Inc. DS51468B-page 89

Page 94: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* To CCM authenticate/encrypt data, you must first call functionaes_ccm_init_encryption_and_mac */

if ((retcode = aes_ccm_init_encryption_and_mac(state,AD_length,length_of_AD_length,AED_length,length_of_AED_length,nonce,nonce_length,length_of_mac,enc_round_keys))!= MCL_SUCCESS){

printf("Parameters are not valid!\n");return 2;

}

/* Then you should process the AD buffer. If there is no AD data,i.e. all data is being both authenticated and encrypted, thenthis stage should be skipped. */

/* Since the necessary lengths of the data were given inaes_ccm_init_encryption_and_mac, it is not necessary to use anyflags (e.g. AES_INIT, AES_FINISH) with the ccmfunctions. aes_ccm_input_AD may be called multiple times, untilall the AD buffer has been processed. */

if ((retcode = aes_ccm_input_AD(state,&out_byte_len,ccm_AD,17,enc_round_keys)) = MCL_SUCCESS){

printf("An error occurred with aes_ccm_input_AD!\n");return 3;

}

if ((retcode = aes_ccm_input_AD(state,&out_byte_len,ccm_AD+17,37,enc_round_keys)) != MCL_SUCCESS){

printf("Error occurred with aes_ccm_input_AD!\n");return 4;

}

/* Since aes_ccm_input_AD records how much data it processes, itknows when it has been given too much data, and will notprocess it. This feature allows users to keep on passing datato the function until the out_byte_len is not equal to thenumber of input bytes. When this happens only the firstout_byte_len bytes of the buffer were processed. */

DS51468B-page 90 © 2006 Microchip Technology Inc.

Page 95: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* For example if we try to process more AD data now, with anothercall to aes_ccm_input AD, then out_byte_len will be 0 */

if ( (retcode = aes_ccm_input_AD(state,&out_byte_len,ccm_AD+54,1000, enc_round_keys)) != MCL_SUCCESS

|| out_byte_len !=0 ) {printf("The whole AD buffer has been processed,\n");printf("so out_byte_len should hold zero now!\n");return 5;

}

/* After the AD buffer is either processed or skipped, then theAED should be processed. If the AED is empty, i.e. all theentries of AED_length are zero, then this step should beskipped. */

/* Since aes_ccm_crypt_AED records how much data it processes, itknows when it has been given too much data, and will notprocess it. This feature allows users to keep on passing datato the function until the out_byte_len is not equal to thenumber of input bytes. In this case only the first out_byte_lenbytes of the buffer were processed. */

/* Also the function knows that it is performing a ccm encryptionoperation, because we have previously calledaes_ccm_init_encryption_and_mac */

if ((retcode = aes_ccm_crypt_AED(state, ans_ct,&out_byte_len,ccm_AED, 13, enc_round_keys)) != MCL_SUCCESS){

printf("A problem with aes_ccm_crypt_AED!\n");return 6;

}

if ((retcode = aes_ccm_crypt_AED(state, ans_ct+13,&out_byte_len,ccm_AED+13, 28, enc_round_keys)) != MCL_SUCCESS){

printf("A problem with aes_ccm_crypt_AED!\n");return 7;

}

© 2006 Microchip Technology Inc. DS51468B-page 91

Page 96: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* Note: the input and the output buffers may be the same foraes_ccm_crypt_AED */

/* If more data is passed to aes_ccm_crypt_AED it will return anout_byte_len of 0, just as in the above example withaes_ccm_input_AD. */

/* Once both AD and AED have been processed if necessary, then youcan obtain the authentication value by calling aes_ccm_get_mac */

/* In this example 8 bytes will be written to the ccm_mac buffer since in aes_ccm_init_encryption_and_mac the mac byte length is set to 8 bytes */

if ((retcode = aes_ccm_get_mac(state, ccm_mac, enc_round_keys))!= MCL_SUCCESS){

printf("A problem with aes_ccm_crypt_AED!\n");return 8;

}

/* Decryption and verification can be done in a similar way. One is assumed to start off with the same buffers, but now the AED buffer holds the ciphertext rather than the plaintext. */

/* CCM uses ONLY aes ENCRYPTION round keys (for authentication,encryption, decryption and verification), so we can reuse theenc_round_keys from above */

/* One first calls aes_ccm_init_decryption_and_verificationwhich takes exactly the same parameters as

aes_ccm_init_encrypt_and_mac */

if ((retcode = aes_ccm_init_decryption_and_verification(state,AD_length,length_of_AD_length,AED_length,length_of_AED_length,nonce,nonce_length,length_of_mac,enc_round_keys))!= MCL_SUCCESS){

printf("The initialization parameters are not valid!\n");return 9;

}

/* Then process the AD buffer if non-empty (unlike encryption, itis done in just one call this time) */

if ((retcode = aes_ccm_input_AD(state,&out_byte_len,ccm_AD,54,enc_round_keys)) != MCL_SUCCESS){

printf("An error occurred with aes_ccm_input_AD!\n");return 10;

}

DS51468B-page 92 © 2006 Microchip Technology Inc.

Page 97: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* Then process the AED bufffer if non-empty (unlike encryption,it is done in just one call this time) */

if ((retcode = aes_ccm_crypt_AED(state, ans_pt,&out_byte_len,ans_ct, 41, enc_round_keys)) != MCL_SUCCESS){

printf("A problem with aes_ccm_crypt_AED!\n");return 11;

}

/* Then we can verify that the mac is correct. Note a verificationfailure is signalled by a return code of MCL_INVALID_MAC. */

if ((retcode = aes_ccm_verify_mac(state, ccm_mac, enc_round_keys))!= MCL_SUCCESS){

printf("The aes ccm AD and AED failed to verify!\n");return 12;

}

/* Note: As is common practice with crypto authentication, if themac fails to verify it is important not to output anyinformation about the plaintext. This means that the plaintextmust be buffered somewhere within a security boundary untilthe data is verified. */

printf("Example code finished successfully!\n");return 0;

}

© 2006 Microchip Technology Inc. DS51468B-page 93

Page 98: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

A.3.6 TDES-ECB Example

#include <stdio.h>#include "ret_codes.h"#include "tdes.h"#include "tdes_ecb.h"

/* Triple DES (TDES) permutes 64 bits to 64 bits Here is an example plaintext */

unsigned char plaintext[]={0x17, 0x38, 0xFA, 0xC9, 0x04, 0xD2, 0x62, 0x7C,

};

/* and this is what the corresponding ciphertext should be when used with the keys below */

unsigned char ciphertext[]={0x11, 0x6a, 0xcd, 0xb4, 0xaf, 0xc0, 0x42, 0x82,

};

/* Triple DES (TDES) is built on top of DES, and makes use of two 64-bit DES keys: key1 and key2. A TDES encryption is equivalent to a standard DES encryption with key1, followed by a standard DES decryption with key2, followed by a standard DES encryption with key1. */

/* First, define key1 and key2 */

const unsigned char keys_one_and_two[] ={0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6, /* key1 */0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF, /* key2 */

};

/* Before performing a TDES encryption or decryption, you should first convert the keys into a format that is particularly efficient for the encryption and decryption algorithms - so called "round keys." The process of transforming a key into its round keys is called key-scheduling and is done by the function des_key_sched. */

/* In this implementation of TDES, a 128-16-bit-word buffer is required to store the round keys */

unsigned short int round_keys[128];

/* In TDES, the same round keys are used by the encryption and decryption algorithms, but this is not necessarily the case for other symmetric key ciphers (e.g. AES) */

int main(void) {unsigned char ans[8];int i;int retcode;

/* First, the keys are transformed to the round keys used by theencryption and decryption algorithms */

DS51468B-page 94 © 2006 Microchip Technology Inc.

Page 99: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

if ((retcode = tdes_key_sched(round_keys, keys_one_and_two))!=MCL_SUCCESS){

printf("Problem generating the round keys!\n");return 1;}

/* Next, 8 bytes (i.e.,one block) of the given plaintext data is encrypted */

if ((retcode = tdes_ecb_encrypt(ans, plaintext, 8,(const unsigned short int *) round_keys)) !=MCL_SUCCESS) {

printf("Problem performing the TDES ECB encryption!\n");return 2;}

/* Then the ciphertext is decrypted */

if ((retcode = tdes_ecb_decrypt(ans, ciphertext, 8,(const unsigned short int *) round_keys)) !=MCL_SUCCESS) {

printf("Problem performing the TDES ECB decryption!\n"); return 3; }

/*Check the answer against the known value of the plaintext */

for (i = 0; i < 8; i++) {if (ans[i] != plaintext[i]) {printf("TDES ECB decryption does not seem to be correct!\n");return 4;}}

/* The number of bytes for ECB mode must be a multiple of 8 (i.e. ECB mode only works for full blocks of encrypted data) */

if ((retcode = tdes_ecb_decrypt(ans, plaintext, 7,(const unsigned short int *) round_keys)) !=MCL_ILLEGAL_SIZE) {

printf("TDES ECB mode only works when the ");printf("number of bytes is a multiple of 8!\n");return 5;}

/* You can encrypt and decrypt more blocks with the ECB mode of operation. For example if tdes_ecb_encrypt has a third argumentof 80, then the first 8 bytes of the plaintext is TDES encrypted with the round keys given, and the output is written to the first 8 bytes of the ciphertext buffer. Then the next 8 bytes of plaintext are encrypted with the same round keys and stored in the next 8 bytes of ciphertext, and so on, until all 80 bytes (i.e. 10 blocks) have been processed. */

/* This mode of operation is NOT recommended for general purposecryptographic encryption of long blocks of data. */

printf("Example code finished successfully!\n");return 0;}

© 2006 Microchip Technology Inc. DS51468B-page 95

Page 100: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

A.3.7 TDES-CBC Example

#include <stdio.h>#include "ret_codes.h"#include "tdes.h"#include "tdes_cbc.h"

const unsigned char tcbc_key[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,

};

const unsigned char tcbc_iv[] = {0xa6, 0x7a, 0x28, 0x1f, 0xea, 0x98, 0x77, 0x15,

};

const unsigned char tcbc_iv2[] = {0xf7, 0x11, 0x9a, 0x2f, 0x84, 0x17, 0xf7, 0x06,

};

const unsigned char tcbc_pt[] = {0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20,0x66, 0x6f, 0x72, 0x20, 0x61, 0x6c, 0x6c, 0x20,

};

const unsigned char tcbc_ct[] = {0x42, 0xb6, 0xa4, 0x0c, 0xec, 0xa8, 0x20, 0xdb, 0x8b, 0x74, 0xbe, 0xe5, 0xb7, 0x4f, 0x4a, 0x4d, 0x60, 0xc5, 0x33, 0x8b, 0xe3, 0xd1, 0xf5, 0xf4,

};

const unsigned char tcbc_ct2[] = {0x97, 0x68, 0xaa, 0x0f, 0x4a, 0xfc, 0x44, 0x2a, 0x8e, 0x06, 0x09, 0x8e, 0x9b, 0x2e, 0x0d, 0xd4, 0x73, 0x21, 0xcf, 0xec, 0xed, 0x79, 0x2f, 0x2a,

};

unsigned short int round_keys[128];unsigned char __attribute__ ((aligned (2))) state[18];

/********************************************************************/intmain(void) {

unsigned char ans[40];unsigned char ans2[40];short int retcode, out_byte_len, total_out;int i, j;int good_op;

/* TDES CBC encryption is a chaining mode of encryption which xorsthe ciphertext of the previous block on to the currentplaintext before performing a standard tdes encryption. Thefirst plaintext block is xor'ed with an initial value (IV). */

DS51468B-page 96 © 2006 Microchip Technology Inc.

Page 101: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* To perform a TDES CBC encryption you must first obtain TDESround keys */

retcode = tdes_key_sched(round_keys, tcbc_key);if (retcode != MCL_SUCCESS) {

printf("Problem producing round keys!\n"); return 1; }

/* The TDES_INIT flag must be set when starting the chaining mode,and the TDES_FINISH flag must be set when ending the chainingmode. When the whole buffer is being processed they may be usedtogether. When supplying plaintext that is neither atthe start or end, then one may use the TDES_DATA_ONLY flag asbelow. The number of input bytes must be a multiple of 8, except when internal padding is being used and it is the lastblock designated by setting the TDES_FINISH flag and the TDES_INTERAL_PAD flag). */

/* Encryption Example 1 Not using internal padding */

/* Before starting the chaining mode, make sure the IV resides in the first 8 bytes of the state */

for (i = 0; i < 8; i++) state[i] = tcbc_iv[i];

/* Then call tdes_cbc_encrypt with the TDES_INIT flag set,which processes the IV, and processes any input bytesgiven to it (in this example the first 8 bytes of plaintext).*/

good_op = 1;

retcode = tdes_cbc_encrypt(state, ans, &out_byte_len, tcbc_pt, 8,(const unsigned short int *) round_keys, TDES_INIT);

/* in normal usage, the out_byte_length will be the same as theinput byte length */

good_op &= (out_byte_len == 8);

/*Encrypt the next 8 bytes of the plaintext */

retcode |= tdes_cbc_encrypt(state, ans+8, &out_byte_len, tcbc_pt+8, 8,(const unsigned short int *) round_keys,

TDES_DATA_ONLY);

/* Check that the correct number of bytes was processed */

good_op &= (out_byte_len == 8);

/* Finally, encrypt the last 8 bytes of the plaintext. The lastblock of plaintext must be signalled by setting theTDES_FINISH flag. */

retcode |=tdes_cbc_encrypt(state,ans+16,&out_byte_len,tcbc_pt+16, 8,(const unsigned short int *) round_keys, TDES_FINISH);

good_op &= (out_byte_len == 8);

© 2006 Microchip Technology Inc. DS51468B-page 97

Page 102: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* Perform the necessary checks and error reports */

if (retcode != MCL_SUCCESS || !good_op) {printf("Problem with tdes_cbc_encrypt!\n");return 2;}

/* Encryption Example 2 (with the same key as example 1) Using internal padding */

/* As mentioned above, in normal use the plaintext byte lengthmust be a multiple of 8, so that whole blocks may thus beprocessed. If the TDES_INTERNAL_PAD flag is set, then the lastblock padded is padded with PKCS #5 padding which allows forthe handling of arbitrary byte-length data. This means theciphertext length may be longer than the plaintext, and forthis reason the length of the buffer is returned to the callingfunction. Note that if the last block is a full 8 bytes, thenPKCS #5 padding will result in a whole extra block beingencrypted. */

/* Initialize the start of state with a different IV */

for (i = 0; i < 8; i++) state[i] = tcbc_iv2[i];

good_op = 1;

/* Encrypt just 22 bytes of the plaintext; first 8 bytes,and then 18 bytes */

/* All but the last call to tdes_cbc_encrypt must have wholeblocks of input data (i.e. byte length a multiple of 8) */

retcode = tdes_cbc_encrypt(state, ans2, &out_byte_len, tcbc_pt, 8, (const unsigned short int *)round_keys, TDES_INIT );

good_op &= (out_byte_len == 8);

/* The TDES_INTERNAL_PAD flag need only be set on the last call,i.e. when TDES_FINISH is also set */

retcode |= tdes_cbc_encrypt(state,ans2+8,t&out_byte_len,tcbc_pt+8,14,(const unsigned short int *) round_keys,TDES_FINISH | TDES_INTERNAL_PAD);

/*The number of output bytes will always be a multiple of 8 */

good_op &= (out_byte_len == 16);

if (retcode != MCL_SUCCESS || !good_op) {printf("Problem with tdes_cbc_encrypt!\n");return 3;}

/* Decryption Example 1 Not using internal padding */

/* A TDES CBC decryption uses the TDES decryption function;

DS51468B-page 98 © 2006 Microchip Technology Inc.

Page 103: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

however, since this uses the same round keys as TDESencryption, you do not need to obtain these again. */

/* Before starting the chaining mode, make sure the IVresides in the first 8 bytes of the state */

for (i = 0; i < 8; i++) state[i] = tcbc_iv[i];

/* The TDES_INIT, TDES_DATA_ONLY and TDES_FINISH flags workexactly the same way in decryption as they do in encryption (see above). Below the data is decrypted with two calls totdes_cbc_decrypt, rather than the three used to encrypt thedata. */

good_op = 1;

/* The first call should have TDES_INIT set */

retcode = tdes_cbc_decrypt(state, ans, &out_byte_len, tcbc_ct, 16,(const unsigned short int *) round_keys, TDES_INIT);

/* Check that the correct number of bytes was processed */

good_op &= (out_byte_len == 16);

/* The last call should have TDES_FINISH set */

retcode|=tdes_cbc_decrypt(state,ans+16,&out_byte_len,tcbc_ct+16,8,(const unsigned short int *) round_keys, TDES_FINISH );

/* Check that the correct number of bytes was processed */

good_op &= (out_byte_len == 8);

if (retcode != MCL_SUCCESS || !good_op) {printf("Problem with tdes_cbc_decrypt!\n");return 4;}

/* Decryption Example 2 (with same key as example 1) Using internal padding */

/* Initialize the state with the correct IV */

for (i = 0; i < 8; i++) state[i] = tcbc_iv2[i];

good_op = 1;

/* Decrypt all the data at once */

retcode = tdes_cbc_decrypt(state,ans2,&out_byte_len,tcbc_ct2,24, (const unsigned short int *) round_keys, TDES_INIT | TDES_FINISH | TDES_INTERNAL_PAD);

/* When internal padding is set, the padding is stripped, andout_byte_len holds the number of bytes of the originalplaintext. If the padding is found to be incorrect,thetdes_cbc_decrypt function returns an MCL_ILLEGAL_PADDING error

return code, and any remaining plaintext will not be output. */

© 2006 Microchip Technology Inc. DS51468B-page 99

Page 104: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

good_op &= (out_byte_len == 22);

if (retcode != MCL_SUCCESS || !good_op) {printf("Problem with tdes_cbc_decrypt!\n");return 5;}

/* Common mistakes */

/* If tdes_cbc_encrypt or tdes_cbc_decrypt fails, it returns a MCL_ILLEGAL_SIZE value. Some possible mistakes with TDES CBCinclude: */

retcode = tdes_cbc_encrypt(state, ans, &out_byte_len, tcbc_pt, 0,(const unsigned short int *) round_keys,TDES_INIT | TDES_FINISH);

if (retcode != MCL_ILLEGAL_SIZE) {printf("Should fail because some data must be processed!\n");return 6;}

retcode = tdes_cbc_encrypt(state, ans, &out_byte_len, tcbc_pt, 7,(const unsigned short int *) round_keys,TDES_INIT | TDES_FINISH);

if (retcode != MCL_ILLEGAL_SIZE) {printf("Should fail ... not an integral number of blocks!\n");return 7;}

printf("Example code finished successfully!\n");return 0;}

DS51468B-page 100 © 2006 Microchip Technology Inc.

Page 105: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

A.3.8 TDES-CBC-MAC Example

#include <stdio.h>#include "ret_codes.h"#include "tdes.h"#include "tdes_cbc.h"

const unsigned char tdes_key[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,

};

const unsigned char message[] = {0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20,0x66, 0x6f, 0x72, 0x20, 0x61, 0x6c,

};

unsigned short int round_keys[128];unsigned char __attribute__ ((aligned (2))) state[18];

/********************************************************************/intmain(void) {

unsigned char ans[8];short int retcode, out_byte_len, total_out;int i, j;

/* TDES CBC MAC is a chaining mode of authentication which xorsthe message data from the previous block on to the currentmessage block before performing a standard tdes encryption. Theoutput of the final block is the authentication value(MAC). The first message block is not xor'ed with anything. */

/* TDES CBC MAC makes use of TDES encryption, so one must firstobtain TDES round keys */

retcode = tdes_key_sched(round_keys, tdes_key);if (retcode != MCL_SUCCESS) {

printf("Problem producing round keys!\n");return 1;}

/* The TDES_INIT flag must be set when starting the chaining mode,and the TDES_FINISH flag must be set when ending the chainingmode. When the whole buffer is being processed they may be usedtogether. When supplying message data that is neither atthe start or end, then one may use the TDES_DATA_ONLY flag asbelow. */

/* tdes_cbc_mac accepts any number of bytes < 65536 as input,i.e., the number of input bytes is not restricted to be a blocklength. Internally the function buffers any partial-blockdata. If there is a partial block of data left over at the end(i.e. when TDES_FINISH is set), then this block is expanded toa full block by appending zeros, before performing the xor'ingand tdes encryption stages to produce the MAC. */

© 2006 Microchip Technology Inc. DS51468B-page 101

Page 106: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* Start the MAC by setting TDES_INIT and processing any giveninput bytes (in this case 6) */

if ((retcode = tdes_cbc_mac(state, NULL, message, 6, round_keys, TDES_INIT)) != MCL_SUCCESS){

printf("Problem performing the TDES CBC MAC!\n");return 2;}

/* For any data that needs to be input before the last chunk weset the TDES_DATA_ONLY flag */

if ((retcode = tdes_cbc_mac(state, NULL, message+6, 7, round_keys, TDES_DATA_ONLY)) != MCL_SUCCESS){

printf("There was a problem performing the tdes cbc mac!\n");return 3;}

/* When the last chunk of data is given we must set theTDES_FINISH flag, and give a buffer in which to store the 8byte MAC result. */

if ((retcode = tdes_cbc_mac(state, ans, message+13, 9, round_keys, TDES_FINISH)) != MCL_SUCCESS){

printf("There was a problem performing the tdes cbc mac!\n");return 4;}

printf("Example code finished successfully!\n");return 0;

}

DS51468B-page 102 © 2006 Microchip Technology Inc.

Page 107: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

A.3.9 TDES-CTR Example

#include <stdio.h>#include "ret_codes.h"#include "tdes.h"#include "tdes_ctr.h"

/* A TDES key to be used in counter mode */

const unsigned char tdes_key[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,

};

/* An IV for counter mode */

const unsigned char tdes_ctr_iv[] = {0x87, 0xf2, 0x7a, 0xe5, 0x11, 0x97, 0x2e, 0xd4,

};

/* Some plaintext */

const unsigned char tdes_ctr_pt[] = {0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74,0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20,0x66, 0x6f, 0x72, 0x20, 0x61, 0x6c,

};

/* The ciphertext corresponding to the above plaintext, IV and key */

const unsigned char tdes_ctr_ct[] = {0x8a, 0xa8, 0xaa, 0xdc, 0xa1, 0xf7, 0xdd, 0xea, 0x37, 0xfc, 0xa2, 0x4f, 0xe5, 0xbf, 0x7e, 0x59, 0x3d, 0xc1, 0x1f, 0xa7, 0x73, 0x0e,

};

unsigned short int round_keys[128];unsigned char __attribute__ ((aligned (2))) state[18];

/********************************************************************/intmain(void) {

unsigned char ans[22];short int retcode, out_byte_len, total_out;int i, j;

/* TDES CTR CRYPT can be used for both encryption anddecryption. It uses the TDES encryption function to make astream of pseudorandom bytes which are xor'ed to the plaintextto create the ciphertext in encryption. In decryption the samepseudorandom bytes are xor'ed to the ciphertext to retrieve theoriginal plaintext. The stream of pseudorandom bytes isobtained by tdes encrypting an initial value (IV) to obtain thefirst 8 pseudorandom bytes, and then incrementing the IV andtdes encrypting to obtain the next 8 pseudorandom bytes, andthen carrying on incrementing and encrypting in this fashion(this is the basis for the name counter (ctr) mode). */

obtain TDES round keys */

© 2006 Microchip Technology Inc. DS51468B-page 103

Page 108: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

retcode = tdes_key_sched(round_keys, tdes_key);if (retcode != MCL_SUCCESS) {

printf("Problem producing round keys!\n");return 1;}

/* The TDES_INIT flag must be set when starting the counter mode,and the TDES_FINISH flag must be set when ending the countermode. When the whole buffer is being processed they may be usedtogether. When supplying message data that is neither atthe start nor the end, you can use the TDES_DATA_ONLY flag asbelow. */

/* The IV must be placed in the first 8 bytes of the statebuffer before any calls to tdes_ctr_crypt */

for (i = 0; i < 8; i++) state[i] = tdes_ctr_iv[i];

/* Call tdes_ctr_crypt with the TDES_INIT set, andprocess any input bytes (6 in this case). The function outputsexactly as many bytes as were input. */

if ((retcode = tdes_ctr_crypt(state, ans, tdes_ctr_pt, 6,round_keys, TDES_INIT)) != MCL_SUCCESS){

printf("Pproblem performing the TDES CTR encryption!\n");return 2;}

/* For any data that needs to be input before the last chunk weset the TDES_DATA_ONLY flag */

if ((retcode = tdes_ctr_crypt(state, ans+6, tdes_ctr_pt+6, 7,round_keys, TDES_DATA_ONLY)) != MCL_SUCCESS){

printf("Problem performing the tdes CTR encryption!\n");return 3;}

/* When the last chunk of data is given, set theTDES_FINISH flag */

if ((retcode = tdes_ctr_crypt(state, ans+13, tdes_ctr_pt+13, 9,round_keys, TDES_FINISH)) != MCL_SUCCESS){

printf("Problem performing the TDES CTR encryption!\n");return 4;}

/* Decryption works in exactly the same way. It also uses the tdesencryption function (to produce the pseudorandom keystream), soyou reuse the same round keys as above */

/* First set the IV */

for (i = 0; i < 8; i++) state[i] = tdes_ctr_iv[i];

/* and then we call tdes_ctr_crypt (this time we've chosen toprocess the whole buffer in one go) */

if ((retcode = tdes_ctr_crypt(state, ans, tdes_ctr_ct, 22,round_keys, TDES_INIT | TDES_FINISH))!= MCL_SUCCESS){

DS51468B-page 104 © 2006 Microchip Technology Inc.

Page 109: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

printf("Problem performing the TDES CTR decryption!\n");return 4;}

printf("Example code finished successfully!\n");return 0;}

© 2006 Microchip Technology Inc. DS51468B-page 105

Page 110: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

NOTES:

DS51468B-page 106 © 2006 Microchip Technology Inc.

Page 111: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Appendix B. Asymmetric Function Examples

B.1 INTRODUCTION

This appendix contains examples of the asymmetric encryption, signing/verification and key agreement functions included in the dsPIC30F Asymmetric Key Embedded Encryption Library.

B.2 HIGHLIGHTS

Included are the following:

• Diffie-Hellman Example• RSA Encryption/Decryption Example• RSA Signing/Verification Example• DSA Example

B.3 ASYMMETRIC FUNCTION EXAMPLES

B.3.1 Diffie-Hellman Example

#include "ret_codes.h"#include "dh.h"#include "drbg.h"#include "sha1.h"

/* The Diffie-Hellman public parameters consist of a large primeinteger p and a large integer g < p. The Open SSL C Library

includes a DH parameter generation function, which produces these quantities. In this example file the buffers hold all of this information. */

/* This example file describes DH-1024, i.e., the publicprime p of 128 bytes. The Library also supports DH-2048, i.e., a prime length of 256 bytes. */

/* DH 1024 bit public prime */

unsigned char p_1024[] = {0xa3, 0x51, 0x78, 0xc0, 0xf9, 0xb3, 0x3e, 0x25,0xe6, 0xd4, 0x73, 0xa4, 0x1b, 0xcf, 0xc1, 0xc9,0xbb, 0x38, 0x18, 0x28, 0x21, 0xd1, 0x6a, 0x25,0xde, 0x75, 0xb7, 0x5b, 0x81, 0xb7, 0x1c, 0x4c,0xb9, 0xf2, 0x45, 0x59, 0x09, 0x76, 0xfc, 0x2c,0x4d, 0x62, 0xdd, 0x2d, 0xfc, 0x29, 0x73, 0xdd,0x61, 0x31, 0xcc, 0x84, 0xcc, 0xb0, 0xcd, 0x75,0xd8, 0x0b, 0x7e, 0x80, 0x2b, 0xb7, 0x53, 0x7b,0x5c, 0x91, 0xef, 0x42, 0x34, 0x98, 0x94, 0x71,0xe0, 0xdd, 0xf6, 0x57, 0x7e, 0x35, 0xb2, 0x81,0x40, 0xfc, 0x13, 0xf9, 0x7c, 0x92, 0x5a, 0x97,0xd1, 0xba, 0xd5, 0xb9, 0x94, 0x6a, 0x0b, 0xf8,0x0b, 0x09, 0x7f, 0x5f, 0x10, 0x6c, 0xf1, 0x34,0xa3, 0x95, 0xb4, 0xaf, 0x80, 0xb9, 0x49, 0xe7,

© 2006 Microchip Technology Inc. DS51468B-page 107

Page 112: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

0xc1, 0xf0, 0x2c, 0x3d, 0xf8, 0x31, 0xfe, 0xc9,0xfb, 0xf4, 0xc1, 0x8b, 0x61, 0x7b, 0x85, 0x13,

};

unsigned short p_byte_len_1024 = 128;

/* DH 1024 bit public generator */

unsigned char g_1024[] = {0x7c, 0x03, 0x77, 0x8b, 0x00, 0xd9, 0xc8, 0x21,0x0c, 0xa1, 0x97, 0x75, 0xae, 0x7c, 0x07, 0xea,0x99, 0xaa, 0xd0, 0xdd, 0x0b, 0x41, 0x3b, 0xb9,0x40, 0xb6, 0x33, 0xb0, 0x71, 0xb3, 0xf6, 0xdb,0xc1, 0x35, 0xa1, 0x01, 0x6b, 0x1f, 0xb2, 0x66,0x81, 0x84, 0x2a, 0x09, 0x2c, 0x9f, 0x77, 0x85,0x27, 0x23, 0xf3, 0x85, 0x7a, 0x29, 0x0d, 0xff,0x99, 0x7c, 0x63, 0x28, 0xa1, 0xa8, 0xb3, 0x4e,0x26, 0x69, 0xd5, 0x3d, 0x5b, 0xc7, 0x08, 0x19,0x2a, 0xe3, 0x25, 0x1a, 0x41, 0x59, 0xe9, 0xf0,0xee, 0xb9, 0x2a, 0x16, 0x0f, 0x76, 0xb3, 0x49,0xb9, 0x01, 0x49, 0xd4, 0x66, 0xdb, 0x57, 0x4f,0x36, 0xa8, 0x63, 0x30, 0x8e, 0xce, 0x6c, 0x61,0x2b, 0xc5, 0x87, 0xa2, 0x1e, 0x7e, 0xf4, 0xeb,0xb4, 0x72, 0xe2, 0x45, 0xa3, 0xb0, 0x36, 0x26,0x5a, 0x4d, 0x8f, 0x6b, 0x3b, 0x01, 0x51, 0x7d,

};

/* The Diffie-Hellman protocol entails two parties generating theirown private quantities x, and public quantities y=g^x. It istherefore important for each party to properly seed theirpseudorandom number generator. Below is the buffer used to seed the DRBG. */

unsigned char seed[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74,

};

/* To simulate the operation of party 2, give abuffer for their DRBG seed */

unsigned char seed_party2[] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,0x51, 0x52, 0x53, 0x54,

};

/* The private key x is then generated to be either a specifiednumber of bits or is chosen randomly in the range 0 < x < p-1.In this example code, x is chosen to be a bit length of 160 bits. To have x chosen randomly in the range0 < x < p-1 you use DH_FULL_EXPONENT (defined in the dh.h file) */

unsigned short int priv_key_bit_len_1024 = 160;

/* In performing both Diffie-Hellman key generation, and shared keycreation, one needs to supply two extra working buffers, one in xdata space, and the other in y data space (because these functionsmake use of the dsPIC MAC instruction). The sizes of these buffers

DS51468B-page 108 © 2006 Microchip Technology Inc.

Page 113: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

should be 2*n_byte_len, and 3*n_byte_len bytes respectively, andshould be aligned in the following way: */

unsigned char __attribute__ ((aligned (64), __section__(".xdata"))) xbuf[256];unsigned char __attribute__ ((aligned (2), __section__(".ydata"))) ybuf[384];

/* buffers used during the protocol: */

unsigned char priv_key[128];/* Buffer for private key x1 */

unsigned char pub_key[128];/* Buffer for public key y1=g^x1 */

unsigned char shared_key[128];/* Buffer for shared key g^(x1*x2) */

/* Here are the corresponding buffers used by the other party *//* (used to simulate correct functionality) */

unsigned char priv_key_party2[128];/* Buffer for private key x2 */

unsigned char pub_key_party2[128];/* Buffer for public key y2=g^x2 */

unsigned char shared_key_party2[128];/* Buffer for shared key g^(x1*x2)*/

intmain(void){

unsigned short int priv_key_byte_len_1024;unsigned short int retcode;int i;

/* The private key should be passed as a byte array todh_create_shared_key. To work out how many bytes it takes tostore a certain bit length, you can do the following: */

priv_key_byte_len_1024 = ((priv_key_bit_len_1024&7) == 0) ?

priv_key_bit_len_1024/8 : 1 + priv_key_bit_len_1024/8;

/* In the case that DH_FULL_EXPONENT is chosen, then x is taken tolie in the range 0 < x < p-1, in which case the private key byte length equals p_byte_len. */

/* In performing Diffie-Hellman key exchange you first seedthe DRBG */

if ((retcode = drbg_seed(xbuf, seed)) != MCL_SUCCESS) {printf("There was an error seeding the DRBG!\n");return 1;}

/* You then generate DH-1024 public and private keys */

if((retcode=dh_generate_keys(pub_key, priv_key, priv_key_bit_len_1024, g_1024, p_1024, p_byte_len_1024,

© 2006 Microchip Technology Inc. DS51468B-page 109

Page 114: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

xbuf, ybuf)) != MCL_SUCCESS) {printf("Error generating DH public and private keys!\n");return 2;}

/* In this example file party 2 is simulated by generating theirpublic and private keys */

/* They first seed the party 2 DRBG */

if ((retcode = drbg_seed(xbuf, seed_party2)) != MCL_SUCCESS) {printf("Error seeding the DRBG for party 2!\n");return 3;}

/* Then they generate party 2 DH-1024 public and private keys */

if ((retcode = dh_generate_keys(pub_key_party2, priv_key_party2, priv_key_bit_len_1024, g_1024, p_1024, p_byte_len_1024, xbuf, ybuf)) != MCL_SUCCESS) {

printf("Error generating party 2's public/private keys!\n");return 4;}

/* Once you have been passed pub_key_party2, you can create theshared key */

if((retcode=dh_create_shared_key(shared_key, pub_key_party2, priv_key, priv_key_byte_len_1024, p_1024, p_byte_len_1024, xbuf,ybuf)) != MCL_SUCCESS) {

printf("Error creating the shared key!\n");return 5;}

/* Similarly party 2 can create the shared key, once given party 1public key */

if ((retcode = dh_create_shared_key( shared_key_party2, pub_key, priv_key_party2,

priv_key_byte_len_1024, p_1024, p_byte_len_1024, xbuf, ybuf)) !=

MCL_SUCCESS) {printf("Error creating party 2's shared key!\n");return 6;}

/* It can easily be tested that these are indeed the same key */

for (i = 0; i < p_byte_len_1024; i++) {if (shared_key[i] != shared_key_party2[i]) {printf("Parties did not create the same shared key!\n");return 7;}

}

/* If you want to produce private keys in the range 0 < x < p-1you call dh_generate_keys in the following manner: */

DS51468B-page 110 © 2006 Microchip Technology Inc.

Page 115: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* DH_FULL_EXPONENT is defined is dh.h */

if((retcode=dh_generate_keys(pub_key, priv_key, DH_FULL_EXPONENT, g_1024, p_1024, p_byte_len_1024, xbuf, ybuf)) != MCL_SUCCESS) {

printf("Error generating DH public and private keys!\n");return 8;}

/* You should recall that when DH_FULL_EXPONENT is specified, theresulting private key takes p_byte_len bytes to store, and sothis should be used as priv_key_byte_len when callingdh_create_shared_key */

printf("Example code finished successfully!\n");return 0;

}

© 2006 Microchip Technology Inc. DS51468B-page 111

Page 116: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

B.3.2 RSA Encryption/Decryption Example

#include "ret_codes.h"#include "rsa_enc_dec.h"#include "drbg.h"#include "sha1.h"

/* The RSA public information consists of a large integer modulus nand public exponent e. The Open SSL library includes an RSA keygeneration function, which on input of a valide, will output a modulus n, and the corresponding privateinformation. In this example file, buffers hold all ofthis information. */

/* RSA public exponent e */

unsigned short int e_byte_len = 3;unsigned char e[] = { /* 2^16 + 1 */

0x01, 0x00, 0x01,};

/* This example file describes RSA-1024, i.e. the publicmodulus n is 128 bytes long. The Microchip Crypto Library alsosupports RSA-2048, i.e. a modulus length of 256 bytes. */

/* RSA 1024 public modulus */

unsigned short int n_byte_len_1024 = 128;unsigned char n_1024[] = {

0xb7, 0x18, 0x67, 0xf4, 0xcb, 0x92, 0x77, 0x61, 0xc6, 0xa6, 0xa0, 0x5b, 0x40, 0x34, 0x39, 0x3a, 0x97, 0xc4, 0xe0, 0x30, 0x86, 0x34, 0xda, 0x6d, 0x2c, 0x90, 0xaf, 0x02, 0xbf, 0x0c, 0x9e, 0xad, 0xdf, 0x13, 0x29, 0xbd, 0x8c, 0x6d, 0x8c, 0x78, 0x34, 0xa0, 0x29, 0x06, 0x72, 0xab, 0x7c, 0x9c, 0x66, 0x81, 0xec, 0x45, 0xb0, 0x54, 0x02, 0x65, 0x3a, 0x35, 0xb0, 0x14, 0xe0, 0xb9, 0xda, 0x4a, 0x0c, 0x21, 0xec, 0x0d, 0xa8, 0x7f, 0x4e, 0xad, 0x3c, 0xf4, 0xcd, 0xc8, 0xcd, 0x16, 0x13, 0xe8, 0x2d, 0xbe, 0xf4, 0xa2, 0x4c, 0x0f, 0xf8, 0x0f, 0x3b, 0x75, 0x2a, 0x79, 0xdc, 0x0c, 0x43, 0x9e, 0x0a, 0xfa, 0x35, 0xad, 0x89, 0x61, 0x69, 0xb7, 0x4c, 0xed, 0x93, 0x99, 0x15, 0x5a, 0x24, 0x9f, 0x66, 0xf7, 0xd5, 0xb2, 0x99, 0x2a, 0x40, 0xfd, 0xed, 0x19, 0x0a, 0x65, 0xff, 0xf7, 0x38, 0x61,

};

/* The private key is a block of (5 * n_byte_len)/2 bytes of datacorresponding to the values p, q, d_p, d_q, q_inv, which are usedin RSA decryption. The information should be obtained from the RSAkey generation function in the accompanying C library, and shouldbe aligned in the following way. */

/* RSA 1024 private key */

unsigned char __attribute__ ((aligned (2))) priv_key_1024[] = {

DS51468B-page 112 © 2006 Microchip Technology Inc.

Page 117: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* p (least significant byte first) */

0x35, 0x42, 0x0e, 0x82, 0x65, 0xf9, 0xb1, 0x9f, 0x1e, 0xcc, 0xef, 0xc7, 0x77, 0x86, 0x0a, 0x41, 0x7d, 0xd0, 0x54, 0x44, 0x9c, 0xa4, 0x6d, 0x88, 0x5c, 0x1f, 0xdf, 0xa6, 0x07, 0x18, 0xc0, 0xaa, 0x62, 0x64, 0x24, 0xe7, 0x8e, 0x43, 0xe0, 0xab, 0xf1, 0x52, 0x55, 0x88, 0x2e, 0x6d, 0x5e, 0x2a, 0x60, 0xaa, 0x27, 0x89, 0x59, 0xed, 0xae, 0x51, 0xa5, 0x5e, 0x9a, 0xdf, 0xe1, 0x62, 0xcb, 0xff,

/* q (least significant byte first) */

0xfd, 0xe2, 0x59, 0x09, 0x6f, 0x68, 0xd5, 0xcd, 0xe0, 0xa8, 0x64, 0x82, 0xfb, 0xbd, 0x52, 0x25, 0x24, 0xe9, 0xeb, 0x15, 0xa6, 0x7c, 0x9b, 0x91, 0xc8, 0x97, 0x8c, 0xa2, 0x47, 0x81, 0x9d, 0xb5, 0xeb, 0xdb, 0x7c, 0x22, 0x4f, 0xa9, 0x28, 0x09, 0x26, 0x17, 0x81, 0xe5, 0x57, 0x2f, 0x0c, 0xb9, 0x99, 0x28, 0x55, 0xbb, 0xe9, 0x21, 0x68, 0xb4, 0x56, 0x11, 0xe0, 0xe1, 0x06, 0x11, 0x3e, 0xb7,

/* d_p (most significant byte first) */

0x66, 0x78, 0x85, 0xbe, 0x52, 0xa3, 0x36, 0xb3, 0x27, 0x8b, 0xda, 0x0d, 0x7a, 0x42, 0x67, 0xa0, 0x6a, 0x98, 0xb5, 0x48, 0x64, 0xd9, 0x39, 0x87, 0x13, 0x01, 0x9e, 0x4e, 0xcb, 0x0d, 0xeb, 0x21, 0x13, 0xa2, 0x2c, 0x7e, 0x34, 0x3d, 0x42, 0x05, 0x01, 0xaa, 0x5a, 0xbd, 0x37, 0x2a, 0x7a, 0xf3, 0x12, 0x71, 0x32, 0xf9, 0x1d, 0x21, 0x55, 0x36, 0x17, 0x67, 0x66, 0xaf, 0x61, 0x70, 0x70, 0xd9,

/* d_q (most significant byte first) */

0x0c, 0xce, 0xfc, 0xd7, 0xb3, 0x50, 0x3b, 0x46, 0x09, 0x44, 0x42, 0x22, 0x99, 0x62, 0xa1, 0x7c, 0xe5, 0x4f, 0x71, 0xbb, 0xbe, 0x22, 0x20, 0xe1, 0x1a, 0xc0, 0xc9, 0xdc, 0xeb, 0x37, 0x39, 0x14, 0x27, 0xd4, 0xc3, 0xa5, 0xa3, 0x3a, 0x1a, 0x9d, 0xfd, 0x77, 0x95, 0xe5, 0xf2, 0x20, 0x54, 0x62, 0x9f, 0x6d, 0x42, 0x34, 0x63, 0x6f, 0xef, 0xd2, 0x0e, 0xf1, 0x3c, 0xe4, 0x8e, 0x0d, 0xc7, 0x6d,

/* q^{-1} mod p (least significant byte first) */

0xa1, 0x00, 0x57, 0x6c, 0x43, 0x78, 0xd1, 0x17, 0xe7, 0x6f, 0xaf, 0xe4, 0x8f, 0x80, 0xba, 0x65, 0xa3, 0x25, 0x1a, 0xf4, 0xf5, 0xdc, 0xac, 0xc0, 0x01, 0x74, 0x31, 0x04, 0xb3, 0xef, 0xa2, 0xa0, 0x66, 0x5a, 0x88, 0xa6, 0xe5, 0x0f, 0x97, 0x51, 0xf5, 0x38, 0xcf, 0xe7, 0xb4, 0xaa, 0xc5, 0x9a, 0xc5, 0xa7, 0xaa, 0xe2, 0x2b, 0xf4, 0xe6, 0xf0, 0x54, 0x37, 0x04, 0x18, 0x1f, 0x86, 0xe8, 0x4d,

};

/* The plaintext length should be between 0 bytes (for the null message),and n_byte_len - 11 bytes (inclusive) */

© 2006 Microchip Technology Inc. DS51468B-page 113

Page 118: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* Encrypt the following plaintext message */

unsigned short int m_byte_len = 10;unsigned char m[]={

0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,0x08, 0x09, 0x0a,

};

/* A necessary requirement of security is that it should be hugelyunlikely that encryptions of the same message, result in the same(public) ciphertext. This is achieved by placing randomness in the message. Thus before an encryption one should make sure thatthe toolkits pseudorandom generator is properly seeded. */

/* You will seed the DRBG with the following array */

const unsigned char seed[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74,

};

/* In performing encryption you need to supply two extra workingbuffers, one in x data space, and the other in y data space(because encryption makes use of the dsPic MAC instruction). Thesizes of these buffers should be 2*n_byte_len, and 3*n_byte_lenbytes respectively, and should be aligned in the following way: */

unsigned char __attribute__ ((aligned(64), __section__(".xdata"))) xbuf[256];unsigned char __attribute__ ((aligned (2), __section__(".ydata"))) ybuf[384];

/* For decryption such buffers are also required, but in this casethey can be slightly smaller - both need to be (3 * n_byte_len)/2bytes long */

/* Here are buffers for the decrypted message and ciphertext */

unsigned char dec_m[128-11];unsigned char c[128];

int main(void){

unsigned short int retcode;unsigned short int dec_m_byte_len;int i, dec_ok;

/* This is how one seeds the DRBG */

if ((retcode = drbg_seed(xbuf, seed)) != MCL_SUCCESS) {printf("An error occurred seeding the drbg!\n");return 1;}

DS51468B-page 114 © 2006 Microchip Technology Inc.

Page 119: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* This is how to encrypt the message m */

if ((retcode = rsa_encrypt(c, m, m_byte_len, n_1024, n_byte_len_1024, e, e_byte_len, xbuf, ybuf)) != MCL_SUCCESS) {

printf("An error occurred encrypting the message!\n");return 2;}

/* This is how you decrypts the ciphertext */

if ((retcode = rsa_decrypt(dec_m, &dec_m_byte_len, c, n_byte_len_1024,priv_key_1024, xbuf, ybuf)) != MCL_SUCCESS) {

printf("An error occurred decrypting the ciphertext!\n");return 3;}

/* and then you can make sure that the message retrieved is equalto the original one */

dec_ok = 1;

dec_ok &= (dec_m_byte_len == m_byte_len);

for (i = 0; i < dec_m_byte_len; i++) {dec_ok &= (dec_m[i] == m[i]);}

if (!dec_ok){printf("Ciphertext did not decrypt to original message!\n");return 4;}

printf("Example code finished successfully!\n");return 0;

}

© 2006 Microchip Technology Inc. DS51468B-page 115

Page 120: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

B.3.3 RSA Signing/Verification Example

#include "ret_codes.h"#include "rsa_sign_ver.h"#include "drbg.h"#include "sha1.h"

/* The RSA public information consists of a large integer modulus nand public exponent e. The Open SSL Library alsoincludes an RSA key generation function, which on input of a valide, will output a modulus n, and the corresponding privateinformation. In this example file the buffers hold all ofthis information. */

/* RSA public exponent e */

unsigned short int e_byte_len = 3;unsigned char e[] = { /* 2^16 + 1 */

0x01, 0x00, 0x01,};

/* This example file describes RSA-1024, i.e., the publicmodulus n is 128 bytes long. The Microchip Crypto Library alsosupports RSA-2048, i.e., a modulus length of 256 bytes. */

/* RSA 1024 public modulus */

unsigned short int n_byte_len_1024 = 128;unsigned char n_1024[] = {

0xb7, 0x18, 0x67, 0xf4, 0xcb, 0x92, 0x77, 0x61, 0xc6, 0xa6, 0xa0, 0x5b, 0x40, 0x34, 0x39, 0x3a, 0x97, 0xc4, 0xe0, 0x30, 0x86, 0x34, 0xda, 0x6d, 0x2c, 0x90, 0xaf, 0x02, 0xbf, 0x0c, 0x9e, 0xad, 0xdf, 0x13, 0x29, 0xbd, 0x8c, 0x6d, 0x8c, 0x78, 0x34, 0xa0, 0x29, 0x06, 0x72, 0xab, 0x7c, 0x9c, 0x66, 0x81, 0xec, 0x45, 0xb0, 0x54, 0x02, 0x65, 0x3a, 0x35, 0xb0, 0x14, 0xe0, 0xb9, 0xda, 0x4a, 0x0c, 0x21, 0xec, 0x0d, 0xa8, 0x7f, 0x4e, 0xad, 0x3c, 0xf4, 0xcd, 0xc8, 0xcd, 0x16, 0x13, 0xe8, 0x2d, 0xbe, 0xf4, 0xa2, 0x4c, 0x0f, 0xf8, 0x0f, 0x3b, 0x75, 0x2a, 0x79, 0xdc, 0x0c, 0x43, 0x9e, 0x0a, 0xfa, 0x35, 0xad, 0x89, 0x61, 0x69, 0xb7, 0x4c, 0xed, 0x93, 0x99, 0x15, 0x5a, 0x24, 0x9f, 0x66, 0xf7, 0xd5, 0xb2, 0x99, 0x2a, 0x40, 0xfd, 0xed, 0x19, 0x0a, 0x65, 0xff, 0xf7, 0x38, 0x61,

};

/* The private key is a block of (5 * n_byte_len)/2 bytes of datacorresponding to the values p, q, d_p, d_q, q_inv, which are usedin RSA signing. The information should be obtained from the RSAkey generation function in the accompanying C library, and should be aligned in the following way. */

/* RSA 1024 private key */

unsigned char __attribute__ ((aligned (2))) priv_key_1024[] = {

DS51468B-page 116 © 2006 Microchip Technology Inc.

Page 121: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* p (least significant byte first) */

0x35, 0x42, 0x0e, 0x82, 0x65, 0xf9, 0xb1, 0x9f, 0x1e, 0xcc, 0xef, 0xc7, 0x77, 0x86, 0x0a, 0x41, 0x7d, 0xd0, 0x54, 0x44, 0x9c, 0xa4, 0x6d, 0x88, 0x5c, 0x1f, 0xdf, 0xa6, 0x07, 0x18, 0xc0, 0xaa, 0x62, 0x64, 0x24, 0xe7, 0x8e, 0x43, 0xe0, 0xab, 0xf1, 0x52, 0x55, 0x88, 0x2e, 0x6d, 0x5e, 0x2a, 0x60, 0xaa, 0x27, 0x89, 0x59, 0xed, 0xae, 0x51, 0xa5, 0x5e, 0x9a, 0xdf, 0xe1, 0x62, 0xcb, 0xff,

/* q (least significant byte first) */

0xfd, 0xe2, 0x59, 0x09, 0x6f, 0x68, 0xd5, 0xcd, 0xe0, 0xa8, 0x64, 0x82, 0xfb, 0xbd, 0x52, 0x25, 0x24, 0xe9, 0xeb, 0x15, 0xa6, 0x7c, 0x9b, 0x91, 0xc8, 0x97, 0x8c, 0xa2, 0x47, 0x81, 0x9d, 0xb5, 0xeb, 0xdb, 0x7c, 0x22, 0x4f, 0xa9, 0x28, 0x09, 0x26, 0x17, 0x81, 0xe5, 0x57, 0x2f, 0x0c, 0xb9, 0x99, 0x28, 0x55, 0xbb, 0xe9, 0x21, 0x68, 0xb4, 0x56, 0x11, 0xe0, 0xe1, 0x06, 0x11, 0x3e, 0xb7,

/* d_p (most significant byte first) */

0x66, 0x78, 0x85, 0xbe, 0x52, 0xa3, 0x36, 0xb3, 0x27, 0x8b, 0xda, 0x0d, 0x7a, 0x42, 0x67, 0xa0, 0x6a, 0x98, 0xb5, 0x48, 0x64, 0xd9, 0x39, 0x87, 0x13, 0x01, 0x9e, 0x4e, 0xcb, 0x0d, 0xeb, 0x21, 0x13, 0xa2, 0x2c, 0x7e, 0x34, 0x3d, 0x42, 0x05, 0x01, 0xaa, 0x5a, 0xbd, 0x37, 0x2a, 0x7a, 0xf3, 0x12, 0x71, 0x32, 0xf9, 0x1d, 0x21, 0x55, 0x36, 0x17, 0x67, 0x66, 0xaf, 0x61, 0x70, 0x70, 0xd9,

/* d_q (most significant byte first) */

0x0c, 0xce, 0xfc, 0xd7, 0xb3, 0x50, 0x3b, 0x46, 0x09, 0x44, 0x42, 0x22, 0x99, 0x62, 0xa1, 0x7c, 0xe5, 0x4f, 0x71, 0xbb, 0xbe, 0x22, 0x20, 0xe1, 0x1a, 0xc0, 0xc9, 0xdc, 0xeb, 0x37, 0x39, 0x14, 0x27, 0xd4, 0xc3, 0xa5, 0xa3, 0x3a, 0x1a, 0x9d, 0xfd, 0x77, 0x95, 0xe5, 0xf2, 0x20, 0x54, 0x62, 0x9f, 0x6d, 0x42, 0x34, 0x63, 0x6f, 0xef, 0xd2, 0x0e, 0xf1, 0x3c, 0xe4, 0x8e, 0x0d, 0xc7, 0x6d,

/* q^{-1} mod p (least significant byte first) */

0xa1, 0x00, 0x57, 0x6c, 0x43, 0x78, 0xd1, 0x17, 0xe7, 0x6f, 0xaf, 0xe4, 0x8f, 0x80, 0xba, 0x65, 0xa3, 0x25, 0x1a, 0xf4, 0xf5, 0xdc, 0xac, 0xc0, 0x01, 0x74, 0x31, 0x04, 0xb3, 0xef, 0xa2, 0xa0, 0x66, 0x5a, 0x88, 0xa6, 0xe5, 0x0f, 0x97, 0x51, 0xf5, 0x38, 0xcf, 0xe7, 0xb4, 0xaa, 0xc5, 0x9a, 0xc5, 0xa7, 0xaa, 0xe2, 0x2b, 0xf4, 0xe6, 0xf0, 0x54, 0x37, 0x04, 0x18, 0x1f, 0x86, 0xe8, 0x4d,

};

© 2006 Microchip Technology Inc. DS51468B-page 117

Page 122: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* In this example file you produce a signature for the followingmessage, and verify it */

const unsigned char m[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,0x79, 0x7a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,0x77, 0x78, 0x79, 0x7a, 0x61, 0x62, 0x63, 0x64,0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75,

};

unsigned short int m_byte_len=93;

/* Rather than directly pass this data to rsa_sign and rsa_verify, ahash of the data is passed, along with a byte string whichidentifies which hash function was used. */

/* In this example file the SHA-1 hash of message is produced. TheASN.1 identification byte string for SHA-1 is defined inrsa_sign_ver.h, and may be gotten in the following fashion: */

const unsigned char sha1_asn_id[] = MCL_SHA1_ASN_ID;unsigned short int sha1_asn_id_byte_len = MCL_SHA1_ASN_ID_BYTE_LEN;

/* In performing RSA verification you must supply two extra workingbuffers, one in x data space, and the other in y data space(because verification makes use of the dsPIC MAC instruction). Thesizes of these buffers should be 2*n_byte_len, and 3*n_byte_lenbytes, respectively, and should be aligned as follows: */

unsigned char __attribute__ ((aligned (64), __section__(".xdata"))) xbuf[256];unsigned char __attribute__ ((aligned (2), __section__(".ydata"))) ybuf[384];

/* For RSA signing such buffers are also required, but in this casethey can be slightly smaller - both need to be (3 * n_byte_len)/2bytes long */

/* here are buffer for the signature s and hash */

unsigned char s[128];unsigned char sha1_hash[20];

int main(void){

unsigned short int retcode;int i;

DS51468B-page 118 © 2006 Microchip Technology Inc.

Page 123: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

/* Obtain the SHA-1 hash of the message (in the first 20 bytes of xbuf) */

if ((retcode = sha1(xbuf, m, m_byte_len, SHA1_INIT | SHA1_FINISH)) != MCL_SUCCESS) {

printf("An error occurred hashing the message!\n");return 1;}

/* copy the hash from xbuf to another buffer, since it is notpossible to reuse xbuf to both point to the hash data, and bethe rsa_sign xbuf working buffer */

for (i = 0; i < 20; i++) { sha1_hash[i] = xbuf[i]; }

/* Sign a message */

/* You cannot reuse xbuf to both give the hash dataand also be the xdata working buffer, so if xbuf is used toform the hash (as above) then the hash data should be copied toa seperate buffer before calling rsa_sign */

if ((retcode = rsa_sign(s, n_byte_len_1024, sha1_hash, 20, sha1_asn_id,

sha1_asn_id_byte_len, priv_key_1024, xbuf, ybuf)) != MCL_SUCCESS) {

printf("Error occurred signing the message hash!\n");return 2;}

/* Verify that the hash and signature pass verification */

if ((retcode = rsa_verify(s, sha1_hash, 20, sha1_asn_id,sha1_asn_id_byte_len, n_1024, n_byte_len_1024, e,e_byte_len, xbuf, ybuf)) != MCL_SUCCESS) {

printf("Signature and message hash did not verify!\n");return 3;}

printf("Example code finished successfully!\n");return 0;

}

© 2006 Microchip Technology Inc. DS51468B-page 119

Page 124: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

B.3.4 DSA Example

#include "ret_codes.h"#include "drbg.h"#include "dsa.h"#include "sha1.h"

/* The DSA public parameters consists of a large prime integer p, asmaller prime q dividing p-1, and a large integer g < p. TheOpen SSL C Library includes a DSA parametergeneration function, which produces these quantities. In thisexample file we have buffers holding all of this information. */

/* The only standardized use of DSA is when p is chosen to be 1024bits (i.e. 128 bytes) */

/* A 1024-bit DSA prime p */

const unsigned char p[] = {0x88, 0x63, 0x2a, 0x4c, 0x2e, 0xe2, 0xbf, 0x81,0xb2, 0x62, 0x6c, 0x30, 0x45, 0xbe, 0x61, 0xdc,0x8a, 0xf3, 0x7f, 0x45, 0x8c, 0x36, 0x19, 0xf2,0x04, 0xc5, 0x7c, 0xca, 0x5d, 0x52, 0xc7, 0x50,0x2f, 0x2b, 0x27, 0x38, 0xec, 0x35, 0x1a, 0x64,0x7c, 0xb3, 0xaa, 0xdd, 0x5c, 0x26, 0x6a, 0x62,0xdd, 0x95, 0x10, 0xdb, 0x9d, 0x07, 0x5f, 0x67,0x98, 0xc2, 0x3f, 0x8a, 0xe3, 0x83, 0x2b, 0xe7,0xc6, 0x86, 0x6d, 0x25, 0xf8, 0xb8, 0x96, 0x74,0x1b, 0x1b, 0xbc, 0xfb, 0x78, 0x43, 0xb6, 0x79,0x05, 0x69, 0x47, 0x65, 0x31, 0xb7, 0x00, 0x35,0xbf, 0xe0, 0xcf, 0x9d, 0x67, 0x9c, 0x0f, 0xa2,0x0d, 0xba, 0x3b, 0xd4, 0x6f, 0x1b, 0x54, 0x5a,0x75, 0xa3, 0x0a, 0xd1, 0x47, 0x10, 0x4f, 0x85,0x45, 0xd4, 0x8b, 0x41, 0x8c, 0x11, 0xd9, 0x35,0xdc, 0xb2, 0x80, 0x25, 0x35, 0xbd, 0x79, 0xfd,

};

/* A 160-bit DSA prime q */

const unsigned char q[] = {0xd7, 0x6c, 0x87, 0x55, 0x07, 0xab, 0xd9, 0xf6, 0x9a, 0xed,0x5a, 0x7f, 0x61, 0x75, 0xdc, 0x50, 0x06, 0x3b, 0xac, 0xbd,

};

/* A DSA generator g */

const unsigned char g[] = {0x54, 0x9a, 0x29, 0x90, 0x15, 0xdd, 0x72, 0xff,0xa2, 0xc5, 0x04, 0x9c, 0x3d, 0x99, 0xfe, 0x2d,0x4c, 0xa5, 0xf2, 0x34, 0xe0, 0x9e, 0x8a, 0x8d,0xce, 0x45, 0x3d, 0x0c, 0x0b, 0x94, 0x61, 0x15,0xf1, 0x53, 0x70, 0xb1, 0x35, 0x72, 0x24, 0x57,0x5b, 0x63, 0x52, 0xc9, 0x08, 0x90, 0xd8, 0x5b,0x25, 0x7b, 0xe1, 0xc4, 0x58, 0x43, 0x13, 0x14,0x38, 0x2c, 0xeb, 0xa1, 0x07, 0x85, 0xe5, 0x38,0x6f, 0x6b, 0xfc, 0x6e, 0xcc, 0x91, 0xda, 0x97,0x30, 0xf9, 0xd9, 0xe5, 0x46, 0x9e, 0x5b, 0x8a,0xe3, 0x43, 0xaf, 0xdd, 0x70, 0xa6, 0xdc, 0x99,0x3d, 0x52, 0x0a, 0x09, 0xbd, 0x8f, 0x6b, 0x81,0x13, 0x61, 0x0a, 0xf9, 0x8b, 0xe1, 0xdf, 0x09,0xca, 0x2b, 0xa2, 0x5d, 0x5f, 0xc1, 0xc3, 0xa9,

DS51468B-page 120 © 2006 Microchip Technology Inc.

Page 125: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

0x2c, 0x63, 0x19, 0xe5, 0x65, 0x7b, 0x93, 0xaf,0x70, 0x65, 0x55, 0x94, 0xb2, 0xed, 0x47, 0xbc,

};

/* Once p,q and g have been created, any party may sign messages. To do so they choose a secret x, 0 < x < q, and reveal the public value y=g^x. It is important for each party to properly seedtheir pseudorandom number generator. Below is the buffer used toseed the DRBG for DSA key generation. */

const unsigned char rand_seed_1[] = {0x42, 0x6e, 0x8f, 0x09, 0x4c, 0xdb, 0x52, 0x91, 0xfa, 0xa3,0x67, 0xff, 0x89, 0xe6, 0x84, 0x7d, 0x18, 0xeb, 0x3d, 0xd2,

};

/* DSA signing also requires choosing a random ephemeral value k, 0 < k < q, for each signature. It is extremely important that the DRBG be properly seeded before any calling dsa_sign. To stressthis fact another seed buffer for DSA signing is given: */

const unsigned char rand_seed_2[] = {0x0c, 0x21, 0xec, 0x0d, 0xa8, 0x7f, 0x4e, 0xad, 0x3c, 0xf4, 0xcd, 0xc8, 0xcd, 0x16, 0x13, 0xe8, 0x2d, 0xbe, 0xf4, 0xa2,

};

/* Here is an example private key */

const unsigned char priv_key[] = {0xba, 0x67, 0xbb, 0x44, 0x8f, 0x22, 0xf5, 0x84, 0xe5, 0xa8,0xa9, 0x82, 0x1f, 0x16, 0x8d, 0x55, 0x76, 0x59, 0xaf, 0xf3,

};

/* Here is the public key corresponding to pub_key[] *//* (with g, p as above) */

const unsigned char pub_key[] = {0x1b, 0x7e, 0xa2, 0xa8, 0x27, 0x50, 0xdc, 0x19,0x7d, 0x6f, 0x76, 0xe6, 0x2e, 0x0f, 0xd3, 0x72,0x16, 0x06, 0xa6, 0xbc, 0x64, 0x1d, 0x3d, 0x83,0x6c, 0xff, 0xaf, 0xc6, 0x84, 0xcd, 0xc5, 0x21,0xb3, 0xc8, 0x55, 0xa5, 0x32, 0x3e, 0x23, 0x4d,0x03, 0x51, 0xb5, 0xdf, 0x84, 0xfc, 0xa4, 0x33,0x4d, 0x13, 0x44, 0xc3, 0x92, 0xd7, 0x39, 0x35,0x19, 0xae, 0x1d, 0xab, 0xc0, 0x90, 0x48, 0x17,0x48, 0xf1, 0x1b, 0xd0, 0x08, 0x16, 0xc9, 0x71,0x2e, 0x11, 0x6c, 0x9c, 0x68, 0x53, 0xa6, 0x01,0x30, 0xe5, 0x93, 0x88, 0x7b, 0x22, 0x53, 0x72,0x72, 0x4e, 0x96, 0x30, 0x50, 0x15, 0x06, 0x64,0xe1, 0xef, 0x41, 0xc8, 0x82, 0x8f, 0x79, 0x91,0x8e, 0x7f, 0xf4, 0x88, 0x87, 0x2c, 0xf1, 0x6f,0xf4, 0x38, 0xb9, 0xc0, 0xab, 0xb6, 0xfd, 0x63,0x11, 0xd6, 0x4a, 0x12, 0xfe, 0x53, 0x7f, 0xe9,

};

© 2006 Microchip Technology Inc. DS51468B-page 121

Page 126: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* In this example file we will produce a signature for the followingmessage, and verify it */

const unsigned char m[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,0x79, 0x7a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,0x77, 0x78, 0x79, 0x7a, 0x61, 0x62, 0x63, 0x64,0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75,

};

unsigned short int m_byte_len=93;

/* Rather than directly pass this data to rsa_sign and rsa_verify, aSHA-1 hash of the data is passed. */

/* Here are buffers for the signature s and SHA-1 hash h */

unsigned char s[40];unsigned char h[20];

/* In performing DSA key generation, DSA signing and DSA verificationyou need to supply two extra working buffers, one in x data space,and the other in y data space (because these functions make use ofthe dsPic MAC instruction). The sizes of these buffers vary withthe functions (see dsa.h for a full specification). The followingbuffers are large enough to be used for all 3 functions. */

unsigned char __attribute__ ((aligned (64), __section__(".xbss") )) xbuf[424];unsigned char __attribute__ ((aligned (2), __section__(".ybss") )) ybuf[384];

/********************************************************************/intmain(void) {

unsigned short int retcode;int i;

/* With the given parameters p, q and g, any party may produce itsown public and private keys */

/* The first step is to make sure that the DRBG is seeded withtruly random data */

if ((retcode = drbg_seed(xbuf, rand_seed_1)) != MCL_SUCCESS) {printf("An error occurred seeding the drbg!\n");return 1;}

/* and then one may obtain the public and private keys in thefollowing way: */

DS51468B-page 122 © 2006 Microchip Technology Inc.

Page 127: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

if ((retcode = dsa_generate_keys(pub_key, priv_key, p, q, g, xbuf, ybuf))

!= MCL_SUCCESS) {printf("Error occurred generating DSA public/private keys!\n");return 2;}

/* The party is then able to sign arbitrary messages m. DSAsignatures involve choosing a random ephemeral quantity k, 0 < k < q, so it is important that the DRBG is properly seededbefore any call to dsa_sign */

if ((retcode = drbg_seed(xbuf, rand_seed_2)) != MCL_SUCCESS) {printf("Error occurred seeding the DRBG!\n");return 3;}

/* The arbitrary length message m is first SHA-1 hashed */

if ((retcode = sha1(xbuf, m, m_byte_len, SHA1_INIT | SHA1_FINISH)) != MCL_SUCCESS) {

printf("Error occurred producing SHA-1 hash of message!\n");return 4;}

/* Then copy the hash from xbuf to another buffer, since it isnot possible to reuse xbuf to both point to the hash data, andbe the xbuf working buffer */

for (i = 0; i < 20; i++) { h[i] = xbuf[i]; }

/* Then DSA sign the message hash */

if ((retcode = dsa_sign(s, h, p, q, g, priv_key, xbuf, ybuf)) != MCL_SUCCESS) {

printf("Error occurred producing the DSA signature!\n");return 5;}

/* Given just the public key, any other party can verify that thisis a valid signature for the message hash */

if ((retcode = dsa_verify(s, h, p, q, g, pub_key, xbuf, ybuf)) !=MCL_SUCCESS) {

printf("The signature and hash did not correctly verify!\n");return 6;}

printf("Example code finished successfully!\n");return 0;}

© 2006 Microchip Technology Inc. DS51468B-page 123

Page 128: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

NOTES:

DS51468B-page 124 © 2006 Microchip Technology Inc.

Page 129: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Appendix C. Hash and Auxiliary Function Examples

C.1 INTRODUCTION

This appendix contains examples of the hash and auxiliary encryption functions included in both the dsPIC30F Embedded Encryption Libraries.

C.2 HIGHLIGHTS

Included are the following:

• DRBG Example• MD5 Example• SHA1 Example

C.3 HASH AND AUXILIARY FUNCTION EXAMPLES

C.3.1 DRBG Example

#include <stdio.h>#include "ret_codes.h"#include "drbg.h"

const unsigned char seed[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74,

};

const unsigned char reseed[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,0x10, 0x11, 0x12, 0x13,

};

unsigned char random[80];

/* the drbg functions need access to a working buffer of 92 bytes *//* allocated in the following fashion */

unsigned char __attribute__ ((aligned (64), __section__(".xbss") )) workbuf[92];

int main(void){

int retcode;

/* IF you want to ... *//* 1. Seed the pseudorandom number generator with seed, *//* which must be 20 bytes *//* 2. Use this seed to generate up to 80 bytes of *//* pseudorandom data to be held in the random array */

© 2006 Microchip Technology Inc. DS51468B-page 125

Page 130: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

/* 3. Update the randomness seed by including the reseed data, *//* which must be 20 bytes *//* 4. And then start to generate some new pseudorandom data *//* THEN you should make sure there is a 92-byte working buffer, *//* and use the drbg_seed() command to initialize the seed */

if ((retcode = drbg_seed(workbuf, seed)) != MCL_SUCCESS) {printf("A problem occured while trying to seed the DRBG.\n");return 1;}

/* You can use the drbg_generate() to generate up to 80 bytes of *//* pseudorandomness (in this case just 20 bytes) */

if ((retcode = drbg_generate(workbuf, random, 20)) != MCL_SUCCESS) {printf("A problem occured trying to generate random data.\n");return 2;}

/* You generate pseudorandom data using drbg_generate(), *//* but to incorporate additional randomness into the DRBG state *//* you can use the drbg_reseed command */

if ((retcode = drbg_reseed(workbuf, reseed)) != MCL_SUCCESS){printf("A problem occured trying to reseed the DRBG.\n");return 3;}

/* after which drbg_generate() can be used again to generate *//* pseudorandom bytes (e.g. 59 this time) */

if ((retcode = drbg_generate(workbuf, random+20, 59)) != MCL_SUCCESS) {

printf("A problem occured trying to generate random data.\n");return 4;}

/* Possible mistakes with pseudorandom number generation include *//* 1. Generation without prior seeding */

if ((retcode = drbg_generate(workbuf, random, 20)) == MCL_DRBG_NOT_INITIALIZED) {

printf("Cannot generate random number unless a seed is set!\n");}

/* 2. Reseeding without prior seeding */

if ((retcode = drbg_reseed(workbuf, reseed)) == MCL_DRBG_NOT_INITIALIZED) {

printf("Cannot reseed the generator unless a seed is set!\n");}

/* 3. Asking for zero bytes of output from the generator */

if ((retcode = drbg_generate(workbuf, random, 0)) != MCL_ILLEGAL_SIZE) {

printf("Asking for no bytes of random data return an error code.\n");

}

printf("Example code finished successfully!\n"); return 0; /* leave main */

}

DS51468B-page 126 © 2006 Microchip Technology Inc.

Page 131: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

C.3.2 MD5 Example

#include <stdio.h>#include "ret_codes.h"#include "md5.h"

const unsigned char some_data[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,0x79, 0x7a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,0x77, 0x78, 0x79, 0x7a, 0x61, 0x62, 0x63, 0x64,0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75,

};

const unsigned char more_data[] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,0x59, 0x5a,

};

const unsigned char the_last_chunk[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,0x38, 0x39, 0x30,

};

/* The md5() function needs access to an 88-byte state buffer *//* allocated in the following fashion */

unsigned char __attribute__ ((aligned (64))) state[88];

int main(void) {int retcode;

/* The first call to md5() must have the MD5_INIT flag set to *//* correctly initialize the state. Data can still be passed in *//* with the MD5_INIT flag set, e.g. the following example first *//* initializes the state, then process 93 bytes of some_data. */

if ((retcode = md5(state, some_data, 93, MD5_INIT))!= MCL_SUCCESS) {

printf("This md5 call exited with an illegal return value!\n");return 1;

}

/* If another 26 bytes need to be added to the hash, you can *//* proceed by calling md5() again; *//* this time with the MD5_DATA_ONLY flag set. *//* NOTE: The state MUST NOT be changed between calls to md5 */

if ((retcode = md5(state, more_data, 26, MD5_DATA_ONLY)) !=MCL_SUCCESS) {

printf("This md5 call exited with an illegal return value!\n");return 2;

© 2006 Microchip Technology Inc. DS51468B-page 127

Page 132: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

}

/* when the final amount of data (11 bytes in this case) *//* is placed into the hash, you should set the MD5_FINISH flag *//* to ensure that the resulting 16-byte MD5 hash is returned *//* (in first 16 bytes of the state buffer) */

if ((retcode = md5(state, the_last_chunk, 11, MD5_FINISH)) != MCL_SUCCESS){

printf("This md5 call exited with an illegal return value!\n");return 3;}

/* each array input to MD5 can hold up to 65535 bytes of data */

printf("Example code finished successfully!\n");return 0;

}

DS51468B-page 128 © 2006 Microchip Technology Inc.

Page 133: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

C.3.3 SHA1 Example

#include <stdio.h>#include "ret_codes.h"#include "sha1.h"

const unsigned char some_data[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,0x79, 0x7a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,0x77, 0x78, 0x79, 0x7a, 0x61, 0x62, 0x63, 0x64,0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,0x71, 0x72, 0x73, 0x74, 0x75,

};

const unsigned char more_data[] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,0x59, 0x5a,

};

const unsigned char the_last_chunk[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,0x38, 0x39, 0x30,

};

/* the sha1() function needs access to a 92-byte state buffer *//* allocated in the following fashion */

unsigned char __attribute__ ((aligned (64), __section__(".xbss") )) state[92];

int main(void) {

int retcode;

/* The first call to sha1() must have the SHA1_INIT flag set to *//* correctly initialize the state. Data can still be passed in *//* with the SHA1_INIT flag set; the following example first *//* initializes the state and then processes 93 bytes of */

/* some_data. */

if ((retcode = sha1(state, some_data, 93, SHA1_INIT)) != MCL_SUCCESS) {

printf("This sha1 call exited with an illegal return value!\n");return 1;}

/* if another 26 bytes need to be added to the hash, you can */ /* proceed by calling sha1() again; this time with the */

/* DATA_ONLY flag set. *//* NOTE: The state MUST NOT be changed between calls to sha1 */

if ((retcode = sha1(state, more_data, 26, SHA1_DATA_ONLY)) !=

© 2006 Microchip Technology Inc. DS51468B-page 129

Page 134: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

MCL_SUCCESS){printf("This sha1 call exited with illegal return value!\n");return 2;}

/* When the final amount of data (11 bytes in this case) *//* is placed into the hash, you should set the SHA1_FINISH flag *//* to ensure that the resulting 20-byte hash is returned *//* (in first 20 bytes of the state buffer) */

if ((retcode = sha1(state, the_last_chunk, 11, SHA1_FINISH)) != MCL_SUCCESS){

printf("This sha1 call exited with an illegal return value!\n");return 3;}

/* each array input to SHA1 can hold up to 65535 bytes of data */

printf("Example code finished successfully!\n");return 0;

}

DS51468B-page 130 © 2006 Microchip Technology Inc.

Page 135: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Appendix D. References

D.1 INTRODUCTION

This chapter provides a list of references to governmental, industrial and defacto standards that are useful in understanding the library functions provided in the dsPIC30F Embedded Encryption Library.

D.2 HIGHLIGHTS

This chapter is organized as follows:

• References to Federal Information Processing Standards (FIPS) and other specifications

• References to textbooks on modern cryptographic practices and algorithms

D.3 REFERENCES TO FEDERAL INFORMATION PROCESSING STANDARDS (FIPS) AND OTHER SPECIFICATIONS

1. “Advanced Encryption Standard” – FIPS Publication 197

Reference for the specification of the 128-bit Advanced Encryption Standard (Rijndael algorithm) implemented in the dsPIC30F Symmetric Key Embedded Encryption Library. The document may be downloaded at:

http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf

2. “Data Encryption Standard” – FIPS Publication 46-3

Reference for the specification of the Triple-Data Encryption Algorithm implemented in the dsPIC30F Symmetric Key Embedded Encryption Library. The document may be downloaded at:

http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf

3. “Computer Data Authentication” – FIPS Publication 113

Reference for implementation of the CBC-MAC authentication mode. The document may be downloaded at:

http://www.itl.nist.gov/fipspubs/fip113.htm

4. “Recommendations for Block Cipher Modes and Techniques” – NIST Special Publication 800-38A

Reference for Counter and Cipher Block Chaining modes of symmetric-key encryption operation. The document may be downloaded at:

http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf

5. “RSA Encryption Standard” – PKCS #1 Version 1.5

Reference for the specification of the Rivest Shamir Adleman (RSA) encryption and signing/verification functions implemented in the dsPIC30F Asymmetric Key Embedded Encryption Library. The document may be downloaded at:

http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/

© 2006 Microchip Technology Inc. DS51468B-page 131

Page 136: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

6. “Diffie-Hellman Key Agreement Standard” – PKCS #3 Version 1.5

Reference for the specification of the Diffie-Hellman Key Agreement Standard implemented in the dsPIC30F Asymmetric Key Embedded Encryption Library. The document may be downloaded at:

http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/

7. “Digital Signature Standard” – FIPS Publication 186-2

Reference for the specification of the Digital Signature Algorithm (DSA) implemented in the dsPIC30F Asymmetric Key Embedded Encryption Library. The document may be downloaded at:

http://csrc.nist.gov/publications/fips/fips186-2/fips186-2-change1.pdf

8. “Secure Hash Standard” – FIPS Publication 180-2

Reference for the specification of the SHA-1 Secure Hash Algorithm implemented in both the dsPIC30F Embedded Encryption Libraries. The document may be downloaded at:

http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf

9. “The MD5 Message Digest Algorithm” – RFC 1321

Reference to the specification of the MD5 Message Digest algorithm implemented in both the dsPIC30F Embedded Encryption Libraries. The document may be downloaded at:

http://www.ietf.org/rfc/rfc1321.txt

10. “Random Number Generation Part 3: Deterministic Random Bit Generators” – American National Standard for Financial Services X9.82 (Draft)

Reference for the specification of the Deterministic Random Bit Generator implemented in both the dsPIC30F Embedded Encryption Libraries. The document may be downloaded by members of X9 at:

http://www.x9.org

D.4 REFERENCES TO TEXTBOOKS ON MODERN CRYPTOGRAPHIC PRACTICES AND ALGORITHMS

1. Handbook of Applied Cryptography by A. Menezes, P. van Oorschot, andS. Vanstone, CRC Press, 1996.

2. Cryptography and Network Security: Principles and Practice by William Stallings, Prentice Hall 27 August, 2002.

3. Applied Cryptography by Bruce Schneier, John Wiley & Sons, 1995.

DS51468B-page 132 © 2006 Microchip Technology Inc.

Page 137: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F EMBEDDED ENCRYPTION

LIBRARIES USER’S GUIDE

Appendix E. Asymmetric Key Embedded Encryption Library Errata

E.1 ERRATA

The dsPIC30F6010/6011/6012/6013/6014 devices may not be used with the Big Inte-ger Arithmetic Package and, consequently, may not be used with the Asymmetric Key Embedded Encryption library. However, the dsPIC30F6010A/6011A/6012A/6013A/6014A devices and all other dsPIC DSC devices do support the library.

© 2006 Microchip Technology Inc. DS51468B-page 133

Page 138: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Embedded Encryption Libraries User’s Guide

NOTES:

DS51468B-page 134 © 2006 Microchip Technology Inc.

Page 139: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

dsPIC30F Symmetric Key Embedded Encryption Library

NOTES:

© 2006 Microchip Technology Inc. DS51468B-page 135

Page 140: dsPIC30F Embedded Encryption Libraries User’s Guideww1.microchip.com/downloads/en/DeviceDoc/51468B.pdf · 1.5 dsPIC30F Embedded Encryption Libraries ... and random number generator

DS51468B-page 136 © 2006 Microchip Technology Inc.

AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://support.microchip.comWeb Address: www.microchip.com

AtlantaAlpharetta, GA Tel: 770-640-0034 Fax: 770-640-0307

BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088

ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075

DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924

DetroitFarmington Hills, MI Tel: 248-538-2250Fax: 248-538-2260

KokomoKokomo, IN Tel: 765-864-8360Fax: 765-864-8387

Los AngelesMission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608

San JoseMountain View, CA Tel: 650-215-1444Fax: 650-961-0286

TorontoMississauga, Ontario, CanadaTel: 905-673-0699 Fax: 905-673-6509

ASIA/PACIFICAustralia - SydneyTel: 61-2-9868-6733 Fax: 61-2-9868-6755

China - BeijingTel: 86-10-8528-2100 Fax: 86-10-8528-2104

China - ChengduTel: 86-28-8676-6200 Fax: 86-28-8676-6599

China - FuzhouTel: 86-591-8750-3506 Fax: 86-591-8750-3521

China - Hong Kong SARTel: 852-2401-1200 Fax: 852-2401-3431

China - QingdaoTel: 86-532-8502-7355Fax: 86-532-8502-7205

China - ShanghaiTel: 86-21-5407-5533 Fax: 86-21-5407-5066

China - ShenyangTel: 86-24-2334-2829Fax: 86-24-2334-2393

China - ShenzhenTel: 86-755-8203-2660 Fax: 86-755-8203-1760

China - ShundeTel: 86-757-2839-5507 Fax: 86-757-2839-5571

China - WuhanTel: 86-27-5980-5300Fax: 86-27-5980-5118

China - XianTel: 86-29-8833-7250Fax: 86-29-8833-7256

ASIA/PACIFICIndia - BangaloreTel: 91-80-2229-0061 Fax: 91-80-2229-0062

India - New DelhiTel: 91-11-5160-8631Fax: 91-11-5160-8632

India - PuneTel: 91-20-2566-1512Fax: 91-20-2566-1513

Japan - YokohamaTel: 81-45-471- 6166 Fax: 81-45-471-6122

Korea - GumiTel: 82-54-473-4301Fax: 82-54-473-4302

Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or 82-2-558-5934

Malaysia - PenangTel: 60-4-646-8870Fax: 60-4-646-5086

Philippines - ManilaTel: 63-2-634-9065Fax: 63-2-634-9069

SingaporeTel: 65-6334-8870Fax: 65-6334-8850

Taiwan - Hsin ChuTel: 886-3-572-9526Fax: 886-3-572-6459

Taiwan - KaohsiungTel: 886-7-536-4818Fax: 886-7-536-4803

Taiwan - TaipeiTel: 886-2-2500-6610 Fax: 886-2-2508-0102

Thailand - BangkokTel: 66-2-694-1351Fax: 66-2-694-1350

EUROPEAustria - WelsTel: 43-7242-2244-399Fax: 43-7242-2244-393Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829

France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79

Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44

Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781

Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340

Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91

UK - WokinghamTel: 44-118-921-5869Fax: 44-118-921-5820

WORLDWIDE SALES AND SERVICE

10/31/05

*DS51468B*