Cryptographic Components for C
Crypto-C
Limit distribution of this document to trusted personnel
Trademarks
License agreement
Distribution
Contents
Cryptography
Quick Start
N t e n t s
Algorithms in Crypto-C
Using Crypto-C 101
Saved State
Non-Cryptographic Operations 151
Public-Key Operations 213
Symmetric-Key Operations 177
Putting It All Together An X9.31 Example
Secret Sharing Operations 305
Glossary 339 Index 349
Appendix a Command-Line Demos 327
List of Figures
A B S a F E C r y p t o C D e v e l o p e r ’s G u i d e
List of Tables
A B S a F E C r y p t o C D e v e l o p e r ’s G u i d e
Preface
MultiPrime RSA
What’s New in Version 5.2.2?
Improved performance
Hardware support
E f a c e
Organization of This Manual
Advanced Encryption Standard AES
Organization of This Manual
Conventions Used in This Manual
Crypto-C procedures to use with algorithm object
Conventions Used in This Manual
Terms and Abbreviations
Terms and Abbreviations
Related Documents
Related Documents
A B S a F E C r y p t o C D e v e l o p e r ’s G u i d e
Http//stdsbbs.ieee.org/groups/1363/index.html
Ieee Standard Specifications for Public-Key Cryptography on
You can get technical support as follows
How to Contact RSA Security
RSA Security Web Site Getting Support and Service
How to Contact RSA Security
Introduction
Algorithms
Crypto-C Toolkit
Secret Sharing
Public-Key Algorithms
Digital Signatures
Elliptic Curve Public-Key Algorithms
Nist Approval and Windows 32-bit Platforms
Cryptographic Standards and Crypto-C
Pkcs Standards and Crypto-C
Nist Standards and Crypto-C
Nist Approval and Windows NT Platforms
Pkcs Compared with Nist
Ansi X9 Standards and Crypto-C
Quick Start
Six-Step Sequence
Six-Step Sequence
Introductory Example
Introductory Example
Include Files
Creating an Algorithm Object
#define Nullptr POINTER0
Where Pointer is defined in aglobal.h
Nullptr is also defined in aglobal.h
Typedef unsigned char *POINTER
Balgorithmobj algorithmObject Algorithm object
Setting the Algorithm Object
Algorithm information
Break
Init
Creating a Key Object
Setting a Key Object
For our example, we use
Key information
Int BSetKeyInfo
Now we can complete the call to BSetKeyInfo
Selecting an Algorithm Chooser
We can now complete our call to BEncryptInit
Update
Saving the Object State optional
Surrender Context
Input data
Output data buffer
Unsigned int
Length of output data
For now, we declare
Unsigned int outputLenUpdate
Unsigned char *encryptedData = Nullptr
Final
If status = BEncryptUpdate
Asurrenderctx *surrenderContext Surrender context
Destroy
Pointer block
For our example, we use the following
Pointer to key object
Balgorithmobj * algorithmObject
If rc4KeyItem.data != Nullptr
Putting It All Together
For this example, call Tfree as follows
Tfree encryptedData
Init If status = BEncryptInit
Introductory Example
EncryptedData = Nullptr End main
If encryptedData != Nullptr
First create the algorithm object
Decrypting the Introductory Example
Creating the Key Object
Decrypting the Introductory Example
Setting the Key Object
DecryptedData = Nullptr
Always destroy objects when you no longer need them
Multiple Updates
Multiple Updates
Break End while
Updatesize
Multiple Updates
Set
Summary of the Six Steps
Include
Create
Final
Page
Cryptography
Cryptography Overview
Cryptography Overview
Symmetric-Key Cryptography
Ciphers
Crypto-C implements the following block ciphers
Block Ciphers
Padding
Ciphers in Crypto-C
2Triple DES Encryption as Implemented in Crypto-C
Triple DES
RC5
RC6
Four Modes
Modes of Operation
3Electronic Codebook ECB Mode
Electronic Codebook ECB Mode
Cipher Feedback CFB Mode
Cipher Block Chaining CBC Mode
5Cipher Feedback CFB Mode
Output Feedback OFB Mode
Stream Ciphers
6Output Feedback Mode OFB
RC4 algorithm with MAC
Message Digests
Message Digests and Pseudo-Random Numbers
Hash-Based Message Authentication Codes Hmac
Password-Based Encryption
Public-Key Cryptography
8DES Key and IV Generation for Password Based Encryption
9Public-Key Cryptography
RSA Algorithm
RSA Algorithm
Modular Math
Prime Numbers
MultiPrime Numbers
Cryptography Overview
1Calculation of 827 mod
Summary
Security
Calculation is shown in Table
Optimal Asymmetric Encryption Padding Oaep
Digital Envelopes
10Digital Envelope
Authentication and Digital Signatures
Cryptography Overview
11RSA Digital Signature
Digital Signature Algorithm DSA
Math
Digital Certificates
Algorithm
Diffie-Hellman Public Key Agreement
Phase
Phase
Parameter Generation
Math
Multiple-Party Key Agreement
Elliptic Curve Cryptography
Finite Field
Elliptic Curve Parameters
Odd Prime Fields
Fields of Even Characteristic
= 0·I ≡ 2·2m-1·Imod2m
Coefficients Over an Odd Prime Field
Elliptic curve parameters
Coefficients Over a Field of Even Characteristic
Point P and its Order
Points of an Elliptic Curve
Is written EFq
Order of an Elliptic Curve
Order of a Point
Point of Prime Order
2Elliptic Curve Parameters
Summary of Elliptic Curve Terminology
Cofactor
Order n of P Is sometimes called the base point
Elliptic Curve Key Pair Generation
Representing Fields of Even Characteristic
Creating the Key Pair
Ecdsa Signature Scheme
Signing a Message
Math
Verifying a Signature
Recall that Q = dP, so
Elliptic Curve Authenticated Encryption Scheme Ecaes
Now recall that s = k-1e+dr mod n, so
Encrypting a Message Using the Public Key
Elliptic Curve Diffie-Hellman Key Agreement
Decrypting a Message Using the Private Key
Phase
13Elliptic Curve Diffie-Hellman Key Agreement
First coordinate of S, xS, is their agreed-upon secret key
Secret Sharing
Key Generation
Working with Keys
Key Escrow
Key Management
Applications of Cryptography
Applications of Cryptography
Ascii Encoding and Decoding
Local Applications
Point-to-Point Applications
Client/Server Applications
Peer-to-Peer Applications
Choosing Algorithms
Choosing Algorithms
Public-Key vs. Symmetric-Key Cryptography
Stream vs. Block Symmetric-Key Algorithms
Key Agreement vs. Digital Envelopes
Block Symmetric-Key Algorithms
Elliptic Curve Algorithms
Secret Sharing and Key Escrow
Interoperability
Security Considerations
Security Considerations
Handling Private Keys
Elliptic Curve Standards
Pseudo-Random Numbers and Seed Generation
Temporary Buffers
Choosing Passwords
DES Weak Keys
Initialization Vectors and Salts
3DES Weak and Semi-Weak Keys
Timing Attacks and Blinding
Stream Ciphers
= mre mod n
Pick a random value r and compute
MD5p padP MD5q padQ m
Choosing Key Sizes
4Summary of Recommended Key Sizes
RSA Keys
RC5 Key Bits and Rounds
Diffie-Hellman Parameters and DSA Keys
RC2 Effective Key Bits
RC4 Key Bits
Elliptic Curve Keys
Algorithms in Crypto-C
Using Crypto-C
Algorithms in Crypto-C
Information Formats Provided by Crypto-C
Basic Algorithm Info Types
BER-Based Algorithm Info Types
1Message Digests
Summary of AIs
PEM-Based Algorithm Info Types
BSAFE1 Algorithm Info Types
5Symmetric Stream Ciphers
Algorithms in Crypto-C 2Message Authentication
3ASCII Encoding
4Pseudo-Random Number Generation
6Symmetric Block Ciphers
Algorithms in Crypto-C 5Symmetric Stream Ciphers
RC2
Algorithms in Crypto-C 6Symmetric Block Ciphers
Key Generation
7RSA Public-Key Cryptography
Oaep
Algorithms in Crypto-C 7RSA Public-Key Cryptography
Digital Signatures
8DSA Public-Key Cryptography
10Elliptic Curve Public-Key Cryptography
Algorithms in Crypto-C 9Diffie-Hellman Key Agreement
11Bloom-Shamir Secret Sharing
10 Elliptic Curve Public-Key Cryptography
12Hardware Interface
Algorithm Info Type
Algorithms in Crypto-C 13Advanced Encryption Standard AES
15Block Cipher Keys
Keys In Crypto-C
Summary of KIs
Keys In Crypto-C
16RSA Public and Private Keys
Keys In Crypto-C 15Block Cipher Keys
17DSA Public and Private Keys
Keys In Crypto-C 18Elliptic Curve Keys
System Considerations In Crypto-C
System Considerations In Crypto-C
Algorithm Choosers
An Encryption Algorithm Chooser
An RSA Algorithm Chooser
Description of AIX962RandomV0 instead of AISHA1Random
Surrender Context
Int *Surrender Pointer handle
Sample Surrender Function
Also gives the form that a surrender function must have
Reserved for future use
Saving State
When to Allocate Memory
Tmalloc Trealloc Tfree Tmemset Tmemcpy Tmemmove Tmemcmp
Memory-Management Routines
Memory-Management Routines and Standard C Libraries
Crypto-C uses the following memory-management routines
Memory Allocation
BER/DER Encoding
Binary Data
Typedef struct unsigned char *data unsigned int len
System Considerations In Crypto-C
Output considerations
Input and Output
Symmetric Block Algorithms
Input constraints
20Input Limits for RSA Pkcs Encryption
General Considerations
DES Keys
Key Size
Public Key Size
Private Key Size
00 C2 58 60 B1
C2 58 60 B1
Using Cryptographic Hardware
Using Cryptographic Hardware
Interfacing with a Bhapi Implementation
2Algorithm Object in a Hardware Implementation
Pkcs #11 Support
Using a Pkcs #11 Device with Crypto-C
Using Cryptographic Hardware
Balgorithmmethod *RSASIGNHWCHOOSER = &AMMD5
Using Cryptographic Hardware
Tfprivate
KeypairGenParams.privateKeyAttributes.tokenFlag =
Now generate
Using Cryptographic Hardware
Using Cryptographic Hardware
Return Behardware
Pkcs #11 Support for DSA Key Pair Generation
Balgorithmmethod *DSAKEYGENCHOOSER = &AMDSAKEYGEN
POINTER&pubKeyData-params
P11KeyGenParams.privateKeyAttributes.keyUsage =
00 00 00 66 a9 47 2d 80 5a
Advanced Pkcs #11
For an RSA private key, it would be this
Digest
CKBYTEPTRseedBuffer, CKULONGseedLen
Hardware Issues
Random Numbers
Ckrv rv Rv =
Using Cryptographic Hardware
Page
Non-Cryptographic Operations
Example in this section corresponds to the file mdigest.c
Message Digests
Creating a Digest
Message Digests
If status = BDigestInit
Your call will be the following
If status = BDigestUpdate
#define Digestlen
BER-Encoding the Digest
Remember to destroy all objects when you are done with them
Saved State
Saving the State of a Digest Algorithm Object
Following example BER-encodes the preceeding sample digest
Item stateInfo = Null
Message Digests
Status = Rsademoealloc break
1Code Sample DigestDataSavedState
Message Digests
Hash-Based Message Authentication Code
Hash-Based Message Authentication Code Hmac
Generate a random 24-byte key using KI24Byte
Hash-Based Message Authentication Code Hmac
Create the key object
RandomAlgorithm, keyData, KEYSIZE, Asurrenderctx *NULLPTR !=
Unsigned char *digestedData unsigned int digestedDataLen
Generating Random Numbers with SHA1
Generating Random Numbers
Generating Random Numbers
Setting The Algorithm Object
Random Seed
Unsigned char *gets char *randomSeed != 0 break
Puts Enter a random seed if status =
If status = BGenerateRandomBytes
Generate
Additional seeding
Generating Independent Streams of Randomness
This step is identical to the previous example
Typedef struct
These steps are identical to the previous example
Steps 4, 5
Item randomSeed AX931RANDOMPARAMS x931Params
Encoding Binary Data To Ascii
Converting Data Between Binary
Converting Data Between Binary and Ascii
If status = BEncodeInit asciiEncoder != 0 break
BDestroyAlgorithmObject &asciiEncoder Tfree asciiEncoding
Decoding ASCII-Encoded Data
If status = binaryDecoding == Nullptr != 0 break
If status = BDecodeInit asciiDecoder != 0 break
BDestroyAlgorithmObject &asciiDecoder Tfree binaryDecoding
Symmetric-Key Operations
Example in this section corresponds to the file descbc.c
Block Ciphers
DES with CBC
Block Ciphers
For new padding schemes
Examples include des, rc5
RC5 parameters
Points at init vector Item
Call BGenerateRandomBytes
Now set up the Bblkcipherwfeedbackparams structure
Format of info supplied to BSetKeyInfo
Depends on cipher type, as follows
Unsigned int outputBufferSize
Decrypting
RC2 Cipher
Now you can set your algorithm object as follows
Init
If rc2KeyItem.data != Nullptr
Use a random number generator to come up with 24 bytes
Update
EncryptedData = Nullptr If rc2KeyItem.data != Nullptr
RC5 Cipher
255 Unsigned int
0x10 Unsigned int
Initialization vector
Unsigned char initVector8 ARC5CBCPARAMS rc5Params
Item rc5KeyItem
Use a random number generator to create 10 bytes
If rc5KeyItem.data != Nullptr
Update
Final
EncryptedData = Nullptr
RC6 Cipher
#define Blocksize Unsigned char initVectorBLOCKSIZE
Setting the Key Data
If rc6KeyItem.data != Nullptr
Break OutputLenTotal = outputLenUpdate + outputLenFinal
Been allocated
AES Cipher
Unsigned char *aesParams
Creating a Key Object
If aesKeyItem.data != Nullptr
Final
Password-Based Encryption
Iteration count
Unsigned char * salt
Init
Tmemset pbeKeyItem.data, 0, Maxpwlen
Update
Final
Page
Public-Key Operations
Generating a Key Pair
Performing RSA Operations
Performing RSA Operations
Where Item is
There is no in generating a key pair
Destroy
Milliseconds Private non-CRT
What is MultiPrime?
MultiPrime
MultiPrime
Two-Prime RSA 48.8 17.5 Three-Prime RSA 10.9
How Many Primes?
Sample
BGetKeyInfo
BGenerateInit
RsaGen
BGenerateKeypair
Set the Algorithm Object
Generating an RSA MultiPrime Key
If status = BGenerateInit keypairGenerator
Distributing an RSA Public Key
BER/DER Encoding
Crypto-C Format
If you looked at the elements of the struct
If status = myPublicKeyBER.data == Nullptr !=
Format of info returned by BGetKeyInfo
Send it off Remember to free any memory you allocated
RSA Public-Key Encryption
Tfree myPublicKeyBER.data
Input constraints
Reference Manual entry on AIPKCSRSAPublic states
#define Blocksize
RSA Private-Key Decryption
If status = BDecryptInit
Raw RSA Encryption and Decryption
Optimal Asymetric Encryption Padding Oaep
MultiPrime
Computing a Digital Signature
RSA Digital Signatures
Setting The Algorithm Object
Entry for the AI in use
Surrender context outlined in The Surrender Context on
Verifying a Digital Signature
If status = BVerifyInit
Update
Generating DSA Parameters
Performing DSA Operations
Performing DSA Operations
Bdsaparamgenparams dsaParams DsaParams.primeBits =
There is no in generating DSA parameters
Generate
Generating a DSA Key Pair
DSA Signatures
Computing a Digital Signature Creating An Algorithm Object
Properly cast Nullptr for the surrender context
#define Maxsiglen
To verify the signature created here, use the same AI
Data and you know its length, your call is the following
Performing Diffie-Hellman Key Agreement
Generating Diffie-Hellman Parameters
Adhparamgenparams
Adhparamgenparams dhParams
There is no in generating Diffie-Hellman parameters
Destroy
Base generator
Distributing Diffie-Hellman Parameters
If you look at the elements of the struct
BER Format
A p t e r 7 P u b l i c K e y O p e r a t i o n s
Item dhParametersBER
Diffie-Hellman Key Agreement
If status = BKeyAgreeInit
Phase
Other party should send their public value and its length
Saving the Object State
Generating Elliptic Curve Parameters
Performing Elliptic Curve Operations
Performing Elliptic Curve Operations
Implementation version
Input of 0 defaults to fieldElementBits
Input of 0 defaults to
Format of info supplied to BSetAlgorithmInfo
Performing Elliptic Curve Operations
No Update step is necessary for parameter generation
GeneralFlag =
Retrieving Elliptic Curve Parameters
Elliptic curve coefficient
Indicates type of base field
It is the prime number
Case that fieldType = Ftfp
If status = output-base.data == Nullptr != 0 break
Aecparams ecParamInfo
If status = output-order.data == Nullptr != 0 break
FreeECParamInfo&ecParamInfo
Sample code, FreeECParamInfo is implemented as follows
Generating an Elliptic Curve Key Pair
Becparams paramInfo
Initialize
There is no Update step for key generation
Aecparams curveParams
Retrieving an Elliptic Curve Key
KIECPublic gives a pointer to an Aecpublickey structure
Public component
Performing Elliptic Curve Operations
Generating a Generic Acceleration Table
Generating Acceleration Tables
End FreeECPubKeyInfo
Format the information
Retrieve the elliptic curve parameters
Aecparams *cryptocECParamInfo Aecparams ecParamInfo
For odd prime field
There is no Update step for building acceleration tables
Build the acceleration table
Allocate memory
Item accelTableItem
Retrieve the public key information
Generating a Public-Key Acceleration Table
FreeECPubKeyInfo&publicKeyInfo
Put the information retrieved in the proper format
Item pubKeyAccelTableItem unsigned int maxTableLen
GeneralFlag = If status = BBuildTableFinal
Performing EC Diffie-Hellman Key Agreement
Build the public-key acceleration table
Item pubKeyAccelTableItem
Create
Optional Set Acceleration Table Info
If status = alicePublicValue == Nullptr != 0 break
If status = aliceSecretValue == Nullptr != 0 break
Performing Ecdsa in Compliance with Ansi
Generating an EC Key Pair
Generating EC Parameters
Computing a Digital Signature Create
Item aTableItem
Build an algorithm chooser with the appropriate AMs
Aecparams *ecParamInfo
Now, using BSignUpdate, pass in the data to be signed
If status = signature == Nullptr != 0 break
Unsigned int signatureLen
Initialized random algorithm in BSignFinal
Destroy all objects that are no longer needed
Use the same AI and digestInfo as you did for signing
Optional Set Public Key Acceleration Table Info
Performing Ecdsa with X9.62-Compliant BER
0x7a
Item stockECParamsBER
ECParamsBER154 = 0x30 0x81
0x52 0xd1
StockECParamsBER.data = ECParamsBER stockECParamsBER.len =
0x79
DataToSign = 0x53
0x68
0x73
Aecparams *ecParamsInfo
Use the same AI as you did for signing
Tfreesignature BDestoryAlgorithmObject &ecDSAVerify
Using Ecaes
Using an EC Key Pair
Using Elliptic Curve Parameters
Ecaes Public-Key Encryption
Now, pass this information into your algorithm object
Optional Acceleration Table
Item accelerationTableItem
Break FieldElementLen = ecParamInfo-fieldElementBits + 7
Final
Steps for decryption are similar to those for encryption
Ecaes Private-Key Decryption
Create an algorithm object
= TmallocmaxDecryptedDataLen
BDecryptUpdate
OutputLenUpdate
MaxDecryptedDataLen = outputLenTotal
Page
Generating Shares
Secret Sharing
Example in this section corresponds to the file scrtshar.c
Secret Sharing
#define Secretsize 16 #define Totalshares
Tfree secretSharecount
If status = secretSharecount == Nullptr != 0 break
Break If status != 0 break
Unsigned int outputLenFinal If status = BEncryptFinal
Use the same AI, AIBSSecretSharing
Reconstructing the Secret
Asurrenderctx *NULLPTR != 0 break If status != 0 break
BDestroyAlgorithmObject &secretReconstructer
Page
Putting It All Together An X9.31 Example
X9.31 Sample Program
X9.31 Sample Program
Bkeyobj privateKey = Bkeyobjnullptr Item randomSeed
Printf ================================================\n
Generating Random Bytes
Static unsigned char f4Data = 0x01, 0x00
Unsigned int status
To create a random algorithm object and set the parameters
Providing the Seed
Generating a Key Pair
Break
Printf ============================= \n
Computing a Digital Signature
RsaVerifyX931. For signing, use rsaSignX931
AX931PARAMS
Break Init
Verifying the Signature
If status !=
Return End GeneralSurrenderFunction
Surrendering Control
Printing the Buffer Contents
Appendix a
Overview of the Demos
Command-Line Demo User’s Guide
Command-Line Demo User’s Guide
Command Line mode
Input Redirection mode
Specifying User Keys
Using Bdemo
Sign a File
Verify a Signed File
Create a File Envelope
Open a File Envelope
Generate a Key Pair
Running Bdemodsa
Using Bdemodsa
Enter any arbitrary string of printable characters
Sign a File
Running Bdemoec
Using Bdemoec
File Reference
File Reference
Table A-1Demo Program Source Files
BSLite Table A-1Demo Program Source Files
BSLite
BSLite
Page
Glossary
Application Programming Interface
Advanced Encryption Standard
Series of steps used to complete a task
American National Standards Institute
O s s a r y
See XOR
Generic security service application program interface
Electronic business Data Interchange
See ECC
An algorithm that generates the subkeys in a block cipher
Process of having a third party hold onto encryption keys
Process that creates a larger key from the original key
Act of creating a key
Data to be encrypted
Extra bits concatenated with a key, password, or plaintext
Private key in the RSA public-key cryptosystem
Secure Multipurpose Internet Mail Extensions
Number extracted from a pseudo- random sequence
Trusted Computer System Evaluation Criteria
Simple Mail Transfer Protocol
Secure Wide Area Network
See secret key
XOR
Page
Index
Ecdsa
D e
A B S a F E C r y p t o C D e v e l o p e r ’s G u i d e
D e
See also RC4 subprime