Cryptographic Components for C
Crypto-C
License agreement
Trademarks
Distribution
Limit distribution of this document to trusted personnel
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
Improved performance
What’s New in Version 5.2.2?
Hardware support
MultiPrime RSA
Advanced Encryption Standard AES
Organization of This Manual
Organization of This Manual
E f a c e
Conventions Used in This Manual
Crypto-C procedures to use with algorithm object
Conventions Used in This Manual
Terms and Abbreviations
Terms and Abbreviations
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
Related Documents
Related Documents
Http//stdsbbs.ieee.org/groups/1363/index.html
Ieee Standard Specifications for Public-Key Cryptography on
RSA Security Web Site Getting Support and Service
How to Contact RSA Security
How to Contact RSA Security
You can get technical support as follows
Introduction
Algorithms
Crypto-C Toolkit
Digital Signatures
Public-Key Algorithms
Elliptic Curve Public-Key Algorithms
Secret Sharing
Pkcs Standards and Crypto-C
Cryptographic Standards and Crypto-C
Nist Standards and Crypto-C
Nist Approval and Windows 32-bit Platforms
Nist Approval and Windows NT Platforms
Pkcs Compared with Nist
Ansi X9 Standards and Crypto-C
Quick Start
Six-Step Sequence
Six-Step Sequence
Include Files
Introductory Example
Creating an Algorithm Object
Introductory Example
Nullptr is also defined in aglobal.h
Where Pointer is defined in aglobal.h
Typedef unsigned char *POINTER
#define Nullptr POINTER0
Algorithm information
Setting the Algorithm Object
Balgorithmobj algorithmObject Algorithm object
Break
Init
For our example, we use
Setting a Key Object
Creating a Key Object
Key information
Int BSetKeyInfo
Now we can complete the call to BSetKeyInfo
Selecting an Algorithm Chooser
Saving the Object State optional
Update
Surrender Context
We can now complete our call to BEncryptInit
Unsigned int
Output data buffer
Length of output data
Input data
Unsigned char *encryptedData = Nullptr
Unsigned int outputLenUpdate
For now, we declare
Final
If status = BEncryptUpdate
Asurrenderctx *surrenderContext Surrender context
Destroy
Pointer to key object
For our example, we use the following
Balgorithmobj * algorithmObject
Pointer block
For this example, call Tfree as follows
Putting It All Together
Tfree encryptedData
If rc4KeyItem.data != Nullptr
Init If status = BEncryptInit
Introductory Example
EncryptedData = Nullptr End main
If encryptedData != Nullptr
Creating the Key Object
Decrypting the Introductory Example
Decrypting the Introductory Example
First create the algorithm object
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
Include
Summary of the Six Steps
Create
Set
Final
Page
Cryptography
Symmetric-Key Cryptography
Cryptography Overview
Ciphers
Cryptography Overview
Padding
Block Ciphers
Ciphers in Crypto-C
Crypto-C implements the following block ciphers
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
Prime Numbers
Modular Math
MultiPrime Numbers
RSA Algorithm
Cryptography Overview
Security
Summary
Calculation is shown in Table
1Calculation of 827 mod
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
Parameter Generation
Phase
Phase
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
Point P and its Order
Coefficients Over a Field of Even Characteristic
Points of an Elliptic Curve
Elliptic curve parameters
Order of a Point
Order of an Elliptic Curve
Point of Prime Order
Is written EFq
Cofactor
Summary of Elliptic Curve Terminology
Order n of P Is sometimes called the base point
2Elliptic Curve Parameters
Elliptic Curve Key Pair Generation
Representing Fields of Even Characteristic
Signing a Message
Ecdsa Signature Scheme
Creating the Key Pair
Math
Verifying a Signature
Now recall that s = k-1e+dr mod n, so
Elliptic Curve Authenticated Encryption Scheme Ecaes
Recall that Q = dP, 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
Ascii Encoding and Decoding
Applications of Cryptography
Local Applications
Applications of Cryptography
Point-to-Point Applications
Client/Server Applications
Peer-to-Peer Applications
Public-Key vs. Symmetric-Key Cryptography
Choosing Algorithms
Stream vs. Block Symmetric-Key Algorithms
Choosing Algorithms
Key Agreement vs. Digital Envelopes
Block Symmetric-Key Algorithms
Elliptic Curve Algorithms
Secret Sharing and Key Escrow
Interoperability
Handling Private Keys
Security Considerations
Elliptic Curve Standards
Security Considerations
Pseudo-Random Numbers and Seed Generation
Temporary Buffers
Choosing Passwords
3DES Weak and Semi-Weak Keys
Initialization Vectors and Salts
DES 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
RC2 Effective Key Bits
Diffie-Hellman Parameters and DSA Keys
RC4 Key Bits
RC5 Key Bits and Rounds
Elliptic Curve Keys
Algorithms in Crypto-C
Using Crypto-C
Basic Algorithm Info Types
Information Formats Provided by Crypto-C
BER-Based Algorithm Info Types
Algorithms in Crypto-C
PEM-Based Algorithm Info Types
Summary of AIs
BSAFE1 Algorithm Info Types
1Message Digests
3ASCII Encoding
Algorithms in Crypto-C 2Message Authentication
4Pseudo-Random Number Generation
5Symmetric Stream Ciphers
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
12Hardware Interface
10 Elliptic Curve Public-Key Cryptography
11Bloom-Shamir Secret Sharing
Algorithm Info Type
Algorithms in Crypto-C 13Advanced Encryption Standard AES
Summary of KIs
Keys In Crypto-C
Keys In Crypto-C
15Block Cipher Keys
17DSA Public and Private Keys
Keys In Crypto-C 15Block Cipher Keys
16RSA Public and Private Keys
Keys In Crypto-C 18Elliptic Curve Keys
Algorithm Choosers
System Considerations In Crypto-C
An Encryption Algorithm Chooser
System Considerations In Crypto-C
An RSA Algorithm Chooser
Description of AIX962RandomV0 instead of AISHA1Random
Surrender Context
Also gives the form that a surrender function must have
Sample Surrender Function
Reserved for future use
Int *Surrender Pointer handle
Saving State
When to Allocate Memory
Memory-Management Routines and Standard C Libraries
Memory-Management Routines
Crypto-C uses the following memory-management routines
Tmalloc Trealloc Tfree Tmemset Tmemcpy Tmemmove Tmemcmp
Binary Data
BER/DER Encoding
Memory Allocation
Typedef struct unsigned char *data unsigned int len
System Considerations In Crypto-C
Symmetric Block Algorithms
Input and Output
Input constraints
Output considerations
20Input Limits for RSA Pkcs Encryption
General Considerations
Public Key Size
Key Size
DES Keys
Private Key Size
00 C2 58 60 B1
C2 58 60 B1
Interfacing with a Bhapi Implementation
Using Cryptographic Hardware
Using Cryptographic Hardware
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 =
For an RSA private key, it would be this
Advanced Pkcs #11
Digest
00 00 00 66 a9 47 2d 80 5a
Random Numbers
Hardware Issues
Ckrv rv Rv =
CKBYTEPTRseedBuffer, CKULONGseedLen
Using Cryptographic Hardware
Page
Non-Cryptographic Operations
Creating a Digest
Message Digests
Message Digests
Example in this section corresponds to the file mdigest.c
If status = BDigestInit
#define Digestlen
If status = BDigestUpdate
Your call will be the following
BER-Encoding the Digest
Remember to destroy all objects when you are done with them
Following example BER-encodes the preceeding sample digest
Saving the State of a Digest Algorithm Object
Saved State
Item stateInfo = Null
Message Digests
Status = Rsademoealloc break
1Code Sample DigestDataSavedState
Message Digests
Hash-Based Message Authentication Code
Hash-Based Message Authentication Code Hmac
Create the key object
Hash-Based Message Authentication Code Hmac
Generate a random 24-byte key using KI24Byte
RandomAlgorithm, keyData, KEYSIZE, Asurrenderctx *NULLPTR !=
Unsigned char *digestedData unsigned int digestedDataLen
Generating Random Numbers
Generating Random Numbers
Generating Random Numbers with SHA1
Setting The Algorithm Object
Random Seed
Unsigned char *gets char *randomSeed != 0 break
Puts Enter a random seed if status =
If status = BGenerateRandomBytes
Generate
This step is identical to the previous example
Generating Independent Streams of Randomness
Typedef struct
Additional seeding
Item randomSeed AX931RANDOMPARAMS x931Params
Steps 4, 5
These steps are identical to the previous example
Converting Data Between Binary and Ascii
Converting Data Between Binary
Encoding Binary Data To 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
DES with CBC
Block Ciphers
Block Ciphers
Example in this section corresponds to the file descbc.c
RC5 parameters
Examples include des, rc5
Points at init vector Item
For new padding schemes
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
Initialization vector
0x10 Unsigned int
255 Unsigned int
Unsigned char initVector8 ARC5CBCPARAMS rc5Params
If rc5KeyItem.data != Nullptr
Use a random number generator to create 10 bytes
Item rc5KeyItem
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
Performing RSA Operations
Performing RSA Operations
Generating a Key Pair
Where Item is
There is no in generating a key pair
Destroy
MultiPrime
What is MultiPrime?
MultiPrime
Milliseconds Private non-CRT
Two-Prime RSA 48.8 17.5 Three-Prime RSA 10.9
How Many Primes?
Sample
RsaGen
BGenerateInit
BGenerateKeypair
BGetKeyInfo
Set the Algorithm Object
Generating an RSA MultiPrime Key
If status = BGenerateInit keypairGenerator
Distributing an RSA Public Key
If you looked at the elements of the struct
Crypto-C Format
BER/DER Encoding
If status = myPublicKeyBER.data == Nullptr !=
Format of info returned by BGetKeyInfo
Tfree myPublicKeyBER.data
RSA Public-Key Encryption
Send it off Remember to free any memory you allocated
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
Performing DSA Operations
Performing DSA Operations
Generating DSA Parameters
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
Performing Elliptic Curve Operations
Performing Elliptic Curve Operations
Generating Elliptic Curve Parameters
Input of 0 defaults to
Input of 0 defaults to fieldElementBits
Format of info supplied to BSetAlgorithmInfo
Implementation version
Performing Elliptic Curve Operations
No Update step is necessary for parameter generation
GeneralFlag =
Retrieving Elliptic Curve Parameters
It is the prime number
Indicates type of base field
Case that fieldType = Ftfp
Elliptic curve coefficient
If status = output-base.data == Nullptr != 0 break
FreeECParamInfo&ecParamInfo
If status = output-order.data == Nullptr != 0 break
Aecparams 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
KIECPublic gives a pointer to an Aecpublickey structure
Retrieving an Elliptic Curve Key
Public component
Aecparams curveParams
Performing Elliptic Curve Operations
End FreeECPubKeyInfo
Generating Acceleration Tables
Generating a Generic Acceleration Table
Aecparams *cryptocECParamInfo Aecparams ecParamInfo
Retrieve the elliptic curve parameters
Format the information
For odd prime field
There is no Update step for building acceleration tables
Item accelTableItem
Allocate memory
Build the acceleration table
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
Build the public-key acceleration table
Performing EC Diffie-Hellman Key Agreement
Item pubKeyAccelTableItem
GeneralFlag = If status = BBuildTableFinal
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
If status = signature == Nullptr != 0 break
Now, using BSignUpdate, pass in the data to be signed
Aecparams *ecParamInfo
Destroy all objects that are no longer needed
Initialized random algorithm in BSignFinal
Use the same AI and digestInfo as you did for signing
Unsigned int signatureLen
Optional Set Public Key Acceleration Table Info
Performing Ecdsa with X9.62-Compliant BER
ECParamsBER154 = 0x30 0x81
Item stockECParamsBER
0x52 0xd1
0x7a
StockECParamsBER.data = ECParamsBER stockECParamsBER.len =
0x68
DataToSign = 0x53
0x73
0x79
Aecparams *ecParamsInfo
Use the same AI as you did for signing
Tfreesignature BDestoryAlgorithmObject &ecDSAVerify
Using Ecaes
Ecaes Public-Key Encryption
Using Elliptic Curve Parameters
Using an EC Key Pair
Item accelerationTableItem
Optional Acceleration Table
Now, pass this information into your algorithm object
Break FieldElementLen = ecParamInfo-fieldElementBits + 7
Final
Create an algorithm object
Ecaes Private-Key Decryption
Steps for decryption are similar to those for encryption
OutputLenUpdate
BDecryptUpdate
MaxDecryptedDataLen = outputLenTotal
= TmallocmaxDecryptedDataLen
Page
Generating Shares
Secret Sharing
Example in this section corresponds to the file scrtshar.c
Secret Sharing
#define Secretsize 16 #define Totalshares
Break If status != 0 break
If status = secretSharecount == Nullptr != 0 break
Unsigned int outputLenFinal If status = BEncryptFinal
Tfree secretSharecount
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
Bkeyobj privateKey = Bkeyobjnullptr Item randomSeed
X9.31 Sample Program
X9.31 Sample Program
Static unsigned char f4Data = 0x01, 0x00
Generating Random Bytes
Unsigned int status
Printf ================================================\n
To create a random algorithm object and set the parameters
Providing the Seed
Generating a Key Pair
Break
RsaVerifyX931. For signing, use rsaSignX931
Computing a Digital Signature
Printf ============================= \n
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 mode
Command-Line Demo User’s Guide
Input Redirection mode
Command-Line Demo User’s Guide
Sign a File
Using Bdemo
Specifying User Keys
Open a File Envelope
Create a File Envelope
Verify a Signed File
Generate a Key Pair
Enter any arbitrary string of printable characters
Using Bdemodsa
Running Bdemodsa
Sign a File
Running Bdemoec
Using Bdemoec
Table A-1Demo Program Source Files
File Reference
File Reference
BSLite Table A-1Demo Program Source Files
BSLite
BSLite
Page
Glossary
Series of steps used to complete a task
Advanced Encryption Standard
American National Standards Institute
Application Programming Interface
O s s a r y
Electronic business Data Interchange
Generic security service application program interface
See ECC
See XOR
Process that creates a larger key from the original key
Process of having a third party hold onto encryption keys
Act of creating a key
An algorithm that generates the subkeys in a block cipher
Private key in the RSA public-key cryptosystem
Extra bits concatenated with a key, password, or plaintext
Data to be encrypted
Secure Multipurpose Internet Mail Extensions
Number extracted from a pseudo- random sequence
Secure Wide Area Network
Simple Mail Transfer Protocol
See secret key
Trusted Computer System Evaluation Criteria
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