ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256...

349
ISC CDK 7 Reference Manual and User’s Guide Jul 18, 2006

Transcript of ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256...

Page 1: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

ISC CDK 7 Reference Manual

and User’s Guide

Jul 18, 2006

Page 2: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...
Page 3: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

Contents

1 ISC Cryptographic Development Kit 1

1.1 Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Namespace Documentation 3

2.1 cdk Namespace Reference . . . . . . . . . . . . . . . . . . . . . . . 3

3 Data Structure Documentation 29

3.1 AES Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 29

3.2 Algorithm Class Reference . . . . . . . . . . . . . . . . . . . . . . . 35

3.3 asn Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 39

3.4 Cert Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 45

3.5 certid Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . 53

3.6 Chain Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . 54

3.7 CMS1 Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . 59

3.8 CRC Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 63

3.9 CRL Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 68

3.10 Date Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 75

3.11 DES Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 77

3.12 DName Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . 85

3.13 EES Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 88

3.14 FParms Class Reference . . . . . . . . . . . . . . . . . . . . . . . . 94

3.15 GParms Class Reference . . . . . . . . . . . . . . . . . . . . . . . . 97

Page 4: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

ii CONTENTS

3.16 GroupData Struct Reference . . . . . . . . . . . . . . . . . . . . . . 100

3.17 ISC_CDK Class Reference . . . . . . . . . . . . . . . . . . . . . . . 103

3.18 Key Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 114

3.19 MD2 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 138

3.20 MD5 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 143

3.21 Nat Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

3.22 num Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 157

3.23 Parameters Struct Reference . . . . . . . . . . . . . . . . . . . . . . 184

3.24 party Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . 185

3.25 Password Class Reference . . . . . . . . . . . . . . . . . . . . . . . 187

3.26 Point Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 189

3.27 PRNG Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . 201

3.28 RC2 Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 207

3.29 RC4 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 211

3.30 recinfo Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . 215

3.31 RSA Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 218

3.32 SHA Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 226

3.33 SHA2 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . 232

3.34 Signature Class Reference . . . . . . . . . . . . . . . . . . . . . . . 237

3.35 Signer Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . 241

3.36 str Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

3.37 TLS Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 256

3.38 tokenop Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . 262

4 File Documentation 265

4.1 aes.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

4.2 alg.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 266

4.3 asn.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

4.4 cdk.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 269

4.5 cdkerr.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . 270

4.6 cert.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 271

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 5: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

CONTENTS iii

4.7 crc.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

4.8 des.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

4.9 ees.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

4.10 hmac.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . 278

4.11 md2.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 279

4.12 md5.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 280

4.13 oid.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

4.14 parms.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . 282

4.15 pass.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 284

4.16 pk.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

4.17 rand.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 289

4.18 rc2.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 290

4.19 rc4.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 291

4.20 sha.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

4.21 str.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 293

4.22 tls.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 294

5 Cookbook 295

5.1 Using the Symmetric Ciphers . . . . . . . . . . . . . . . . . . . . . . 295

5.2 Using the Message Digest Functions . . . . . . . . . . . . . . . . . . 302

5.3 Using the str and num Classes . . . . . . . . . . . . . . . . . . . . . 305

5.4 Processing X.509v3 Certificates and CRLs . . . . . . . . . . . . . . . 307

5.5 Handling Public and Private Keys . . . . . . . . . . . . . . . . . . . 315

5.6 Handling PKCS PDUs (including CMS) . . . . . . . . . . . . . . . . 329

5.7 Pseudorandom Numbers . . . . . . . . . . . . . . . . . . . . . . . . 339

5.8 Implementing a Simple TLS Client . . . . . . . . . . . . . . . . . . . 340

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 6: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...
Page 7: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

Chapter 1

ISC CryptographicDevelopment Kit

User’s Guide

1.1 Table of Contents

• Legal Notices and Contact Information

• Standards Compliance

• NIST Algorithm and Key Size Recommendations

• Summary of Data Structures

• Description of Header Files

• Class Hierarchy

• Cookbook (Sample Code)

1.1.1 Indices

• Index of Data Types

• Index of Global Functions

Page 8: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2 ISC Cryptographic Development Kit

1.2 Introduction

CDK 7.0’s object oriented API provides a wide range of cryptographic primitives aswell as certificate and CRL processing functions. The provided algorithms include:

• public key algorithms: RSA, DSA/ECDSA, DH/ECDH

(digital signatures, encryption/decryption, key agreement)

• symmetric ciphers: AES, TDES/DES/DESX, EES, RC2, RC4

(most FIPS-approved modes of operation are supported)

• message digests: SHA-1, SHA-256/384/512, MD2, MD5, CRC-32

• keyed hash functions: HMAC-SHA1, HMAC-MD5

• pseudorandom number generation; primality testing

• high-precision arithmetic (rings of integers, finite fields, elliptic curves)

Among the CDK’s more advanced features are:

• X.509v3 certificate/CRL parsing and creation

• PKCS#7/#8/#10/#12 PDU parsing and creation

(including support for the parsing and creation of S/MIME CMS PDUs)

• an OCSP client

• a simple SSL/TLS client

CDK 7.0 is available on a wide range of platforms:

• Windows 9x/ME/NT/2000/XP, PocketPC 2002/ARM, Windows Mobile 5

• Solaris/SPARC, Solaris/Intel, SunOS/SPARC

• HP-UX 10/11

• IBM AIX (32- and 64-bit versions)

• Linux i86

• Mac OS X

• SGI IRIX 6.x

• Compaq Tru64

• Cray UNICOS

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 9: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

Chapter 2

Namespace Documentation

2.1 cdk Namespace Reference

2.1.1 Detailed Description

Namespace for all CDK symbols.

Data Structures

• class AES

Implementation of the NIST Advanced Encryption Standard ("AES"), FIPS 197.

• class Algorithm

Base class for tracking algorithm errors and internal system states.

• struct recinfo

Lowest level data type used to process ASN.1 data.

• struct Date

Data type used for date and time processing.

• struct asn

Internal data type used for ASN.1 BER/DER encoding/decoding.

• class ISC_CDK

Base class for FIPS 140-1 on-demand self-tests, error state tracking, and convenienceutilities.

Page 10: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4 Namespace Documentation

• struct DNameData type used for representing and processing X.500 distinguished names.

• struct CertData type used for encoding and decoding individual X.509 certificates.

• struct ChainData type used for processing X.509 certificate chains.

• struct CRLData type used for creating and processing certificate revocation lists.

• struct certidData type used to detect matching certificates.

• struct tokenopData type used by callbacks to do private key operations, possibly on a hardwaretoken.

• struct SignerData type used for CMS digital signature operations.

• struct CMS1Data type used for in-memory PKCS #7 operations (RFC 3852 CMS).

• class CRCImplementation of the IEEE 32-bit CRC.

• class DESImplementation of the NIST Data Encryption Standard (DES, TDES, and variants),FIPS 46-3/81.

• class EESImplementation of the NIST EES ("Skipjack"), FIPS 185.

• class MD2Implementation of the RFC 1319 MD2 message digest.

• class MD5Implementation of the RFC 1321 MD5 message digest.

• struct GroupData

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 11: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 5

Data type used to store parameters for particular Abelian groups.

• class PasswordImplementation of the NIST FIPS 181 Automated Password Generator.

• class NatData type used to represent elements of various algebraic objects.

• struct ParametersBase class for arithmetic parameters (used to define various algebraic structures).

• class FParmsData type used to specify arithmetic parameters for various rings and fields.

• struct numImplementation of the arithmetic in various groups, rings, and fields.

• class GParmsData type used to specify arithmetic parameters for various groups, including ellipticcurves.

• class PointData type used to represent the elements of, and abstract the operations in, variousAbelian groups, including elliptic curves.

• class RSAImplementation of RSA-based cryptographic schemes.

• class SignatureData type used for digital signature operations.

• struct KeyClass Key is the principal data type used for public and private keys and all relatedcryptographic operations.

• class PRNGImplementation of the NIST FIPS 186-2 Pseudorandom Number Generator.

• struct RC2Implementation of the RC2 symmetric block cipher.

• class RC4Implementation of the RC4 stream cipher.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 12: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

6 Namespace Documentation

• class SHA

Implementation of the NIST Secure Hash Algorithm (SHA/SHA-1), FIPS 180-1.

• class SHA2

Implementation of the Extended NIST Secure Hash Algorithms (SHA-256/-384/-512),FIPS 180-2.

• struct str

Class str is somewhat similar to the STL std::string type.

• struct party

Internal data type used by the implementation of class TLS to encapsulate variouscryptographic operations.

• struct TLS

Data type used to implement SSLv2/TLS. For details, see RFC 2246.

Typedefs

• typedef double TimeT

Data type used to extend UNIX time format.

• typedef int(CALLBACK ∗) TokenDecryptCallback (tokenop &)

Callback type for decryption operations.

• typedef int(CALLBACK ∗) TokenSignCallback (tokenop &)

Callback type for signature operations.

• typedef int(CALLBACK ∗) TokenVerifyCallback (tokenop &)

Callback type for signature validation.

• typedef Nat ∗ nat

pointer to a Nat

• typedef Nat const ∗ cnat

const pointer to a Nat

• typedef unsigned int nword

basic word type

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 13: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 7

• typedef nword ∗ nwordppointer to a nword

• typedef nword const ∗ cnwordpconst pointer to a nword

Enumerations

• enum tags {

Bool = 0x01,

Int = 0x02,

Bit = 0x03,

Oct = 0x04,

Obj = 0x06,

Asc = 0x13,

Asc0C = 0x0C,

Asc14 = 0x14,

Asc16 = 0x16,

Asc1A = 0x1A,

T_Date17 = 0x17,

T_Date = 0x18,

Unicode = 0x1E,

Seq = 0x30,

Set = 0x31 ,

VarStr = 0x0B,

VarInt = 0x1F,

VarNum = 0x0D,

VarDate = 0x0E,

TagOption = 0x0F,

BitTrunc = -3 }ASN.1 tags for simple types and aliases for various BER/DER encoding bytes.

• enum DSAParms {

FIPSEXAMPLE = 0,

ISCDSA512 = 1,

ISCDSA768 = 2,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 14: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

8 Namespace Documentation

ISCDSA1024 = 3,

ISCDSA2048 = 4,

ISCDSA4096 = 5 }Parameter IDs for DSA.

• enum NISTCurves {

NISTP192 = 0,

NISTP224 = 1,

NISTP256 = 2,

NISTP384 = 3,

NISTP521 = 4,

NISTK163 = 5,

NISTB163 = 6,

NISTK233 = 7,

NISTB233 = 8,

NISTK283 = 9,

NISTB283 = 10,

NISTK409 = 11,

NISTB409 = 12,

NISTK571 = 13,

NISTB571 = 14 }Parameter IDs for NIST FIPS 186-2 elliptic curves; SECG and ANSI X.9.62 aliasesare also provided below.

• enum hashes {

hNone,

hMD2 = 1,

hMD4 = 2,

hMD5 = 3,

hSHA1 = 4,

hSHA256 = 5,

hSHA384 = 6,

hSHA512 = 7,

hSHA224 = 8 }Algorithm IDs for various hash functions (values are consistent with MS CAPI)

• enum groupsIDs for various groups/algorithms (for internal use only).

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 15: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 9

Functions

• _cdkpub TimeT timegmt ()

Get the current time (GMT) in UNIX format.

• _cdkpub num loaddec (const char ∗s)

Convert an ASCII string of decimal digits to the corresponding num.

• _cdkpub int parsedname (const str &dn, str &ASCII, int opt=0)

Parse an ASN.1 encoded DN into a printable string.

• _cdkpub int parsesign (const str &cer, asn &body, asn &oid, asn &sig, intrecode_der=0)

Parse the signature out of an ASN.1 encoded certificate.

• _cdkpub str makesign (const str &body, const str &oid, const str &sig)

Create an X.509 certificate (or CRL) by combining its body with an issuer’s signature.

• _cdkpub num makep1 (int htype, const num &hvalue, int n)

Pad a message digest value according to PKCS#1v1.5 (for signing).

• _cdkpub int parsep1 (const str &b, int &htype, asn &hvalue)

Parse a PKCS#1v1.5 padded message digest.

• _cdkpub str makep7 (const Chain &chn)

Create an ASN.1 encoded PKCS#7 PDU containing a set of certificates.

• _cdkpub int parsep7 (const str &b, Chain &chn)

Parse an ASN.1 encoded PKCS#7 PDU containing one or more certificates.

• _cdkpub str makep8 (const str &oid, const str &prv, const str &pwd)

Create an ASN.1 encoded PKCS#8 PDU containing an encrypted private key.

• _cdkpub int parsep8 (const str &p8, const str &pwd, asn &oid, asn &prv)

Decrypt and parse an ASN.1 encoded PKCS#8 PDU containing an encrypted privatekey.

• _cdkpub str makep10raw (const str &dn, const str &oid, const str &pub, conststr &attributes)

Create an ASN.1 encoded PKCS#10 certificate request.

• _cdkpub int parsep10 (const str &p10, asn &dn, asn &oid, asn &pub, asn &at-tributes)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 16: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

10 Namespace Documentation

Parse an ASN.1 encoded PKCS#10 certificate request.

• _cdkpub int parse_crmf (const str &req, asn &dn, asn &oid, asn &pub, asn &at-tributes)

Parse an ASN.1 encoded CRMF PDU.

• _cdkpub str make_cmmf (const Chain &chn, int requestid)

Create a Netscape CMMF PDU.

• _cdkpub str makep12 (const str &cer, const str &oid, const str &prv, const str&pwd, const str &frname, const str &id)

Create an ASN.1 encoded PKCS#12 PDU.

• _cdkpub int parsep12 (const str &p12, const char ∗pwd, Chain &chn, asn &oid,asn &prv, asn &crl)

Decrypt and parse an ASN.1 encoded PKCS#12 PDU containing an encrypted privatekey.

• _cdkpub int checkcert (const str &certissuer, const str &certsubject)

Validate one ASN.1 encoded certificate against another.

• _cdkpub int checksign (const str &cer, const str &oidhash, const str &msg, conststr &sig)

Validate an ASN.1 encoded digital signature over a specified message.

• _cdkpub int checksignhash (const str &cer, const num &h, const str &sig)

Validate an ASN.1 encoded digital signature over a specified hash value.

• typedef int (CALLBACK ∗TokenCallback)(tokenop &)

General callback type.

• _cdkpub str make_ocsp_req (const str &caCert, const str &subCert, const str&nonce)

Create an OCSP request.

• _cdkpub int check_ocsp (const str &req, const str &resp, asn &signinfo, TimeT&revTime, asn &certs, asn &dn)

Check an OCSP response.

• _cdkpub int check_signinfo (const str &cer, const str &signinfo)

Check an OCSP response.

• _cdkpub str asn1ber_to_der (const asn &ber)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 17: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 11

Convert a BER-encoded (indefinite length encoding) to a DER-encoded PDU.

• template<class T> str HMAC (const str &key, const str &msg)Compute an HMAC over a specified message using a specified key.

• _cdkpub str A2O (const str &strDotted)Convert human readable OID’s in dotted notation to binary equivalent for encoding.

• _cdkpub str genkeyp5 (const str &pwd, const str &salt, int iter, int n)Generate a (symmetric) key from a password as per PKCS#5.

• _cdkpub str genkeyp12 (const str &pwd, const str &salt, int n, int iter, int id)Generate a (symmetric) key from a password as per PKCS#12.

• _cdkpub int DSA_GenerateParameters (const str &seed, int nq, int np, num &q,num &p, num &g, int &counter, int start=0, int h=2, int v=1)

Generate DSA parameters as per FIPS 186-2.

• _cdkpub int rsadecrypt (const num &pq, const num &d, const num &input, str&x)

Raises input to the power d, mod pq, and strips pkcs1 padding.

• _cdkpub double mytime1 ()Get system time.

• _cdkpub str getrand1 (int n)Get a str object containing a specified number of pseudorandom bytes.

• _cdkpub str getrand2 (int n)Get a str object containing a specified number of pseudorandom bytes.

• template<class T> void operator+= (T &t, const str &x)Operator template used to add() a str object to an object of type T.

• template<class T> str tostr2 (const T &t)Template used to convert an object of type T into a str object.

• template<class T> str DoHash (const str &x, int v=1)Template used to hash a str object using a message digest of type T.

• _cdkpub str hex (const char ∗hexstr)Create a str object by parsing a specified string of hex digits.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 18: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

12 Namespace Documentation

Variables

• GroupData const DSA_Parms [6]• GroupData const NIST_Curves [15]• GroupData const ANSI_Curves [1]• GroupData const MicrosoftDRM

2.1.2 Enumeration Type Documentation

2.1.2.1 enum tags

ASN.1 tags for simple types and aliases for various BER/DER encoding bytes.

Enumerator:

Bool BOOLEAN.

Int INTEGER.

Bit BIT STRING.

Oct OCTET STRING.

Obj OBJECT IDENTIFIER.

Asc PrintableString.

Asc0C UTF8String.

Asc14 TeletexString, T61String.

Asc16 IA5String.

Asc1A VisibleString.

T_Date17 UTCTime.

T_Date GeneralizedTime (w/ 4-digit year).

Unicode BMPString.

Seq SEQUENCE OF.

Set SET OF.

VarStr VarStr.

VarInt VarInt.

VarNum VarNum.

VarDate VarDate.

TagOption TagOption.

BitTrunc for RFC 3280 named bit lists

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 19: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 13

2.1.2.2 enum DSAParms

Parameter IDs for DSA.

Use this enum to access the built in DSA parmeters

(e.g., cdk::str strOID = cdk::DSA_Parms[cdk::ISCDSA2048].oid()).

Enumerator:

FIPSEXAMPLE NIST FIPS 186-2 sample DSA parametersISCDSA512 ISC 512-bit DSA parametersISCDSA768 ISC 768-bit DSA parametersISCDSA1024 ISC 1024-bit DSA parametersISCDSA2048 ISC 2048-bit DSA parametersISCDSA4096 ISC 4096-bit DSA parameters

2.1.2.3 enum NISTCurves

Parameter IDs for NIST FIPS 186-2 elliptic curves; SECG and ANSI X.9.62 aliasesare also provided below.

Use this enum to access built-in ECDSA parameters

(e.g., cdk::str strOID = cdk::NIST_Curves[cdk::NISTP192].oid()).

Enumerator:

NISTP192 NIST curve P-192; SECG secp192r1; ANSI X9.62 an-six9p192r1/prime192v1

NISTP224 NIST curve P-224; SECG secp224r1; ANSI X9.62 ansix9p224r1NISTP256 NIST curve P-256; SECG secp256r1; ANSI X9.62 an-

six9p256r1/prime256v1NISTP384 NIST curve P-384; SECG secp384r1; ANSI X9.62 ansix9p384r1NISTP521 NIST curve P-521; SECG secp521r1; ANSI X9.62 ansix9p521r1NISTK163 NIST curve K-163; SECG sect163k1; ANSI X9.62 ansix9t163k1NISTB163 NIST curve B-163; SECG sect163r2; ANSI X9.62 ansix9t163r2NISTK233 NIST curve K-233; SECG sect233k1; ANSI X9.62 ansix9t233k1NISTB233 NIST curve B-233; SECG sect233r1; ANSI X9.62 ansix9t233r1NISTK283 NIST curve K-283; SECG sect283k1; ANSI X9.62 ansix9t283k1NISTB283 NIST curve B-283; SECG sect283r1; ANSI X9.62 ansix9t283r1NISTK409 NIST curve K-409; SECG sect409k1; ANSI X9.62 ansix9t409k1NISTB409 NIST curve B-409; SECG sect409r1; ANSI X9.62 ansix9t409r1NISTK571 NIST curve K-571; SECG sect571k1; ANSI X9.62 ansix9t571k1NISTB571 NIST curve B-571; SECG sect571r1; ANSI X9.62 ansix9t571r1

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 20: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

14 Namespace Documentation

2.1.2.4 enum hashes

Algorithm IDs for various hash functions (values are consistent with MS CAPI)

Enumerator:

hNone undefined

hMD2 MD2 (RFC 1319)

hMD4 MD4 (RFC 1320)

hMD5 MD5 (RFC 1321)

hSHA1 SHA-1 (FIPS 180-1).

hSHA256 SHA-256 (FIPS 180-2).

hSHA384 SHA-384 (FIPS 180-2).

hSHA512 SHA-512 (FIPS 180-2).

hSHA224 SHA-224 (FIPS 180-2).

2.1.3 Function Documentation

2.1.3.1 _cdkpub TimeT cdk::timegmt ()

Get the current time (GMT) in UNIX format.

Returns:

a TimeT object representing the current time (GMT) in UNIX format (a doublecontaining the number of seconds since Jan. 1 1970)

2.1.3.2 _cdkpub num cdk::loaddec (const char ∗ s)

Convert an ASCII string of decimal digits to the corresponding num.

Parameters:

s a pointer to a buffer containing the decimal number (in ASCII) to be converted

Returns:

a num object representing the value of s.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 21: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 15

2.1.3.3 _cdkpub int cdk::parsedname (const str & dn, str & ASCII, int opt = 0)

Parse an ASN.1 encoded DN into a printable string.

Parameters:

dn an ASN.1 encoded distinguished name.

ASCII an output buffer for the printable string representing dn

opt a format indicator:0 for RDNs in the order they are encournterd in dn with no intervening spaces1 for an uppercase string representation of dn2 for RDNs in the reverse order of their occurance in dn

Returns:

0 (success)non-zero on failure.

2.1.3.4 _cdkpub int cdk::parsesign (const str & cer, asn & body, asn & oid, asn& sig, int recode_der = 0)

Parse the signature out of an ASN.1 encoded certificate.

Parameters:

cer the binary ASN.1 encoded certificate to be parsed

body an output buffer for the certificate body (tbsCertificate)

oid an ASN.1 encoded OID identifying the issuer’s signature algorithm

sig an output buffer for the issuer’s signature (ASN.1 encoded)

recode_der

Returns:

0 (success)1, if the certificate cannot be parsed

2.1.3.5 _cdkpub str cdk::makesign (const str & body, const str & oid, const str& sig)

Create an X.509 certificate (or CRL) by combining its body with an issuer’s signature.

Parameters:

body the binary ASN.1 encoded certificate body (tbsCertificate)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 22: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

16 Namespace Documentation

oid an ASN.1 encoded OID identifying the issuer’s signature algorithm

sig the ASN.1 encoded issuer’s signature over the body

Returns:

a str containing the complete ASN.1 encoded certificate(If an error occurs, the returned str has length 0.)

Remarks:

This function doesn’t actually sign the certificate body. You may call Key::Sign()and then Signature::toasn1() to obtain the input value for the sig parameter.

2.1.3.6 _cdkpub num cdk::makep1 (int htype, const num & hvalue, int n)

Pad a message digest value according to PKCS#1v1.5 (for signing).

Parameters:

htype type of message digest in hvalue

hvalue hash value to be padded

n required number of output bytes

Returns:

the message digest padded according to PKCS#1v1.5

Remarks:

htype == hNone is allowed and pads according to TLS/SSL (36 bytes, no oid)

2.1.3.7 _cdkpub int cdk::parsep1 (const str & b, int & htype, asn & hvalue)

Parse a PKCS#1v1.5 padded message digest.

Parameters:

b padded hash value to be parsed

htype output buffer for the message digest type

hvalue output buffer for the unpadded message digest value

Returns:

0 (success)non-zero (failure)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 23: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 17

2.1.3.8 _cdkpub str cdk::makep7 (const Chain & chn)

Create an ASN.1 encoded PKCS#7 PDU containing a set of certificates.

Parameters:

chn a set of binary ASN.1 encoded certificates (concatenated together)

Returns:

a str containing an ASN.1 encoded PKCS #7 PDU containing the certificates

2.1.3.9 _cdkpub int cdk::parsep7 (const str & b, Chain & chn)

Parse an ASN.1 encoded PKCS#7 PDU containing one or more certificates.

Parameters:

b the binary ASN.1 encoded PKCS #7 PDU to be parsedchn an output buffer for the certificates (concatenated together)

Returns:

0 (success)non-zero (failure)

2.1.3.10 _cdkpub str cdk::makep8 (const str & oid, const str & prv, const str &pwd)

Create an ASN.1 encoded PKCS#8 PDU containing an encrypted private key.

Parameters:

oid the algorithm identifier of the private key in prvprv the ASN.1 encoded private key to be encryptedpwd the password for PKCS#8 PBE

Returns:

a binary ASN.1 encoded private key encrypted in accordance with PKCS #8(On failure, a str of length 0.)

Remarks:

On failure the returned str has 0 length. In this case Algorithm::isErrorState()should be called to determine whether or not the CDK has entered its hard errorstate.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 24: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

18 Namespace Documentation

2.1.3.11 _cdkpub int cdk::parsep8 (const str & p8, const str & pwd, asn & oid,asn & prv)

Decrypt and parse an ASN.1 encoded PKCS#8 PDU containing an encrypted privatekey.

Parameters:

p8 the PKCS#8 PDU to be decrypted and parsed

pwd the password used to encrypt the PKCS#8 PDU

oid an output buffer for the algorithm ID of the private key

prv an output buffer for the (unencrypted) private key

Returns:

0 (success)2 (parse error)3 (invalid password)CDK_ERROR_STATE, if the CDK is in the hard error state

2.1.3.12 _cdkpub str cdk::makep10raw (const str & dn, const str & oid, conststr & pub, const str & attributes)

Create an ASN.1 encoded PKCS#10 certificate request.

Parameters:

dn an ASN.1 encoded subject distinguished name

oid the ASN.1 encoded algorithm ID of the public key

pub the ASN.1 encoded public key to include in the reqeust

attributes additional attributes (i.e., extensions) to be included in the request

Returns:

a str containing the binary ASN.1 encoded PKCS#10 certificate request(On failure, a str of length 0.)

2.1.3.13 _cdkpub int cdk::parsep10 (const str & p10, asn & dn, asn & oid, asn& pub, asn & attributes)

Parse an ASN.1 encoded PKCS#10 certificate request.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 25: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 19

Parameters:

p10 the binary ASN.1 encoded PKCS #10 certificate request to be parsed

dn an output buffer for the subject DN

oid an output buffer for the algorith ID of the public key

pub an output buffer for the public key

attributes an output buffer for additional attributes (i.e., extensions) found in therequest

Returns:

0 (success)1, 2 (parse error)3 (invalid signature)CDK_ERROR_STATE

2.1.3.14 _cdkpub int cdk::parse_crmf (const str & req, asn & dn, asn & oid, asn& pub, asn & attributes)

Parse an ASN.1 encoded CRMF PDU.

Parameters:

req the binary ASN.1 encoded CRMF PDU to be parsed (see RFC 4211)

dn an output buffer for the subject DN

oid an output buffer for the algorith ID of the public key

pub an output buffer for the public key

attributes an output buffer for additional attributes (i.e., extensions) found in therequest

Returns:

0 (success)1, 2 (parse error)3 (invalid signature)CDK_ERROR_STATE

Remarks:

Private key escrow is not supported.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 26: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

20 Namespace Documentation

2.1.3.15 _cdkpub str cdk::make_cmmf (const Chain & chn, int requestid)

Create a Netscape CMMF PDU.

Parameters:

chn certificate chain containing newly issued certificaterequestid request id returned by Netscape browser during enrollment

Returns:

a CMMF PDU that Netscape will, upon import, associate with the correspondingprivate key.

2.1.3.16 _cdkpub str cdk::makep12 (const str & cer, const str & oid, const str &prv, const str & pwd, const str & frname, const str & id)

Create an ASN.1 encoded PKCS#12 PDU.

Parameters:

cer a binary ASN.1 encoded certificate (or a concatenation of binary ASN.1 en-coded certificates) to be included in the PDU

oid the ASN.1 encoded algorithm ID of the private keyprv an ASN.1 encoded private key (encrypted or not)pwd the password to use for encryption of the private keyfrname an optional "friendly" name to include in the PDUid an identifier to include in the PDU

Returns:

a str containing the binary ASN.1 encoded PKCS #12 PDU(On failure, a str of length 0.)

Remarks:

On failure the returned str has 0 length. In this case Algorithm::isErrorState()should be called to determine whether or not the CDK has entered its hard errorstate.

2.1.3.17 _cdkpub int cdk::parsep12 (const str & p12, const char ∗ pwd, Chain &chn, asn & oid, asn & prv, asn & crl)

Decrypt and parse an ASN.1 encoded PKCS#12 PDU containing an encrypted privatekey.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 27: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 21

Parameters:

p12 the binary ASN.1 encoded PKCS#12 PDU to be decrypted and parsed

pwd the password used to encrypt the PDU

chn an output buffer for all certificates found in the PDU

oid an output buffer for the algorithm ID of the private key

prv an output buffer for the the private key (in the clear or encrypted according toPKCS#8 or PKCS#5)

crl an output buffer for all CRLs found in the PDU

Returns:

0 (success)1 (parse error)2 (invalid password)CDK_ERROR_STATE

2.1.3.18 _cdkpub int cdk::checkcert (const str & certissuer, const str &certsubject)

Validate one ASN.1 encoded certificate against another.

Parameters:

certissuer the binary ASN.1 encoded certificate of the purported issuer

certsubject the binary ASN.1 encoded certificate to be validated

Returns:

0 (certificate is valid)CDK_SUBJECT_CERT_EXPIREDCDK_ISSUER_CERT_EXPIREDCDK_WRONG_ISSUER_CERTCDK_ISSUER_CERT_NOT_CACDK_CANT_PARSE_SUBJECT_CERTCDK_CANT_PARSE_ISSUER_CERTCDK_INVALID_SIGNATURECDK_ERROR_STATE

2.1.3.19 _cdkpub int cdk::checksign (const str & cer, const str & oidhash, conststr & msg, const str & sig)

Validate an ASN.1 encoded digital signature over a specified message.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 28: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

22 Namespace Documentation

Parameters:

cer the binary ASN.1 encoded certificate of the purported signer

oidhash the algorithm ID of the message digest function

msg the data that was purportedly signed

sig the binary ASN.1 encoded signature to be validated

Returns:

0 (signature is valid)CDK_CERT_EXPIREDCDK_CANT_PARSE_CERTCDK_INVALID_SIGNATURECDK_ERROR_STATE

2.1.3.20 _cdkpub int cdk::checksignhash (const str & cer, const num & h, conststr & sig)

Validate an ASN.1 encoded digital signature over a specified hash value.

Parameters:

cer the binary ASN.1 encoded certificate of the purported signer

h the message digest that was purportedly signed

sig the binary ASN.1 encoded signature to be validated

Returns:

0 (signature is valid)CDK_CERT_EXPIREDCDK_CANT_PARSE_CERTCDK_INVALID_SIGNATURECDK_ERROR_STATE

2.1.3.21 _cdkpub str cdk::make_ocsp_req (const str & caCert, const str &subCert, const str & nonce)

Create an OCSP request.

Parameters:

caCert issuer certificate

subCert subject certificate whose validity is to be tested

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 29: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 23

nonce a 16-byte random value

Returns:

a str representation of the request PDU suitable for transmission to an OCSP re-sponder

2.1.3.22 _cdkpub int cdk::check_ocsp (const str & req, const str & resp, asn &signinfo, TimeT & revTime, asn & certs, asn & dn)

Check an OCSP response.

Parameters:

req the original requestresp the responder’s responsesinfo the responder’s signature on the responserevTime if certificate has been revoked, the time of revocationcertsdn

Returns:

0 certificate is valid1 certificate has been revoked

Remarks:

If this function returns 0 or 1, the signature on the response should be checkedusing check_signinfo().

2.1.3.23 _cdkpub int cdk::check_signinfo (const str & cer, const str & signinfo)

Check an OCSP response.

Parameters:

req the original requestresp the responder’s response

Returns:

0 certificate is valid1 certificate has been revoked2 certificate status is unknown (responder is not authoritative for this issuer)3 protocol error4 invalid signature on response

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 30: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

24 Namespace Documentation

2.1.3.24 _cdkpub str cdk::asn1ber_to_der (const asn & ber)

Convert a BER-encoded (indefinite length encoding) to a DER-encoded PDU.

Parameters:

ber a BER-encoded PDU

Returns:

on success, a str containing the DER-encoded PDUthe input str is returned unchanged if it was already DER-encoded or a parsingerror occurred.

2.1.3.25 str cdk::HMAC (const str & key, const str & msg)

Compute an HMAC over a specified message using a specified key.

Parameters:

key the secret shared key

msg the data to be hashed

Returns:

a cdk::str representation of the message digest

Remarks:

HMAC is explicitly instantiated (for those systems whose compilers don’t supportthe template approach) only for SHA-1 and MD5, but the supplied inline sourcecode for this function in hmac.h makes it clear how to instantiate HMAC for otherhash functions.See FIPS 198 and RFC 2104 for details about HMAC.

2.1.3.26 _cdkpub str cdk::A2O (const str & strDotted)

Convert human readable OID’s in dotted notation to binary equivalent for encoding.

Parameters:

strDotted is a string like "OID.1.2.3.4" or "1.2.3.4"

Returns:

A CDK string object containing the binary representation of the OID.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 31: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 25

2.1.3.27 _cdkpub str cdk::genkeyp5 (const str & pwd, const str & salt, int iter,int n)

Generate a (symmetric) key from a password as per PKCS#5.

Parameters:

pwd a pointer to the password

salt the salt value

iter the iteration count (512 or higher is recommended)

n the length of the desired symmetric key in bytes

Returns:

a str containing the symmetric key generated as per PKCS#5

2.1.3.28 _cdkpub str cdk::genkeyp12 (const str & pwd, const str & salt, int n,int iter, int id)

Generate a (symmetric) key from a password as per PKCS#12.

Parameters:

pwd a pointer to the password

salt the salt value

n the length of the desired symmetric key in bytes

iter the iteration count (1024 or higher is recommended)

id the type of key to generate: 1 = symmetric encryption key, 2 = IV, 3 = MAC

Returns:

a str containing the symmetric key generated as per PKCS#12

2.1.3.29 _cdkpub int cdk::DSA_GenerateParameters (const str & seed, int nq,int np, num & q, num & p, num & g, int & counter, int start = 0, int h =2, int v = 1)

Generate DSA parameters as per FIPS 186-2.

Parameters:

seed a SEED value

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 32: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

26 Namespace Documentation

nq the length of the desired q value in bits

np length of the desired p value in bits

q num that is to receive the q value (order of g modulo p)

p num that is to receive the p value (a large prime)

g num that is to receive the g value (subgroup generator of order q modulo p)

counter int that is receive the iteration count required to select p

start initial value of the counter

h base value use to select g = h∧(p-1)/q; NIST tends to use 2, ISC uses 7.

v flag used to select hash function: 0=SHA, 1=SHA-1

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_SEEDCDK_INVALID_ALG_PARAMSCDK_INVALID_ITERATION_COUNT

2.1.3.30 _cdkpub int cdk::rsadecrypt (const num & pq, const num & d, constnum & input, str & x)

Raises input to the power d, mod pq, and strips pkcs1 padding.

Parameters:

pq the RSA modulus.

d the RSA private exponent

input the value to decrypt

x the output value.

Remarks:

This function will attempt to remove PKCS#1 padding. If the result isn’t paddedaccording to PKCS#1 the result is undefined.

Returns:

0 (success)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 33: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

2.1 cdk Namespace Reference 27

2.1.3.31 _cdkpub double cdk::mytime1 ()

Get system time.

Returns:

a double representation of the current high precision system time.

2.1.3.32 _cdkpub str cdk::getrand1 (int n)

Get a str object containing a specified number of pseudorandom bytes.

Parameters:

n the number of random bytes to generate

Returns:

a str with n "low-grade" random bytes

Note:

This function is for internal use only!

2.1.3.33 _cdkpub str cdk::getrand2 (int n)

Get a str object containing a specified number of pseudorandom bytes.

Parameters:

n the number of random bytes to generate

Returns:

a str with n random bytes

Note:

This method creates a temporary PRNG object, calls gens(n), and returns the re-sult.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 34: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

28 Namespace Documentation

2.1.3.34 _cdkpub str cdk::hex (const char ∗ hexstr)

Create a str object by parsing a specified string of hex digits.

Parameters:

hexstr a pointer to a buffer containing a null-terminated string of hex digits

Returns:

a str object containing the binary data encoded in hexstr

2.1.4 Variable Documentation

2.1.4.1 GroupData const DSA_Parms[6]

Several NIST and ISC DSA parameters (see enum DSAParms for array indices).

2.1.4.2 GroupData const NIST_Curves[15]

Various NIST FIPS 186-2 elliptic curves (see enum NISTCurves for array indices).

2.1.4.3 GroupData const ANSI_Curves[1]

The ANSI x9.62-J.2.1 elliptic curve over GF(2191 ).

2.1.4.4 GroupData const MicrosoftDRM

The elliptic curve used by Microsoft for digital rights management (DRM 2.0).

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 35: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

Chapter 3

Data Structure Documentation

3.1 AES Class Reference

#include <aes.h>

Inheritance diagram for AES:

AES

Algorithm

Collaboration diagram for AES:

AES

Algorithm

3.1.1 Detailed Description

Implementation of the NIST Advanced Encryption Standard ("AES"), FIPS 197.

AES is a 16-byte block cipher with a key size of 128, 192, or 256 bits.

Page 36: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

30 Data Structure Documentation

Buffers may be encrypted or decrypted "in place," i.e., in == out is allowed in crypt().

Usage flow:AES() // instantiate a new AES objectinit() // specify the direction, key, mode, and IV (if required)setcounter() // only required in CTR modecrypt() // perform the encrypt or decrypt operation

Recommendations for strict FIPS 140-1 compliance:All supported modes of AES are FIPS compliant.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Symmetric Ciphers.

3.1.2 References

AES (also known as "Rijndael") is specified in FIPS 197.

Public Types

• ENCRYPT

crypt() call performs encryption

• DECRYPT

crypt() call performs decryption

• ECB = 1

Electronic Code Book mode.

• CBC = 2

Cipher Block Chaining mode.

• CFB8

8-bit Cipher Feedback mode

• CFB64

64-bit Cipher Feedback mode

• CFB128

128-bit Cipher Feedback mode

• OFB

Output Feedback mode.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 37: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.1 AES Class Reference 31

• CTR

Counter mode (NIST SP800-38A).

• enum dirs {

ENCRYPT,

DECRYPT }

Direction values.

• enum modes {

ECB = 1,

CBC = 2 ,

CFB8,

CFB64,

CFB128,

OFB,

CTR }

Modes of operation.

Public Member Functions

• ∼AES ()

Destructor. Calls clear().

• int init (enum dirs dir, int keybytes, const char ∗key, enum modes md=ECB,const char ∗IV=0)

Initialize the AES object.

• int setcounter (int bytes, const char ∗counter)

Set counter for CTR mode.

• int crypt (int bytes, const char ∗inbuf, char ∗outbuf)

Encrypt or decrypt a specified buffer.

• void clear (void)

Clear the AES object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 38: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

32 Data Structure Documentation

3.1.3 Member Enumeration Documentation

3.1.3.1 enum dirs

Direction values.

Enumerator:

ENCRYPT crypt() call performs encryptionDECRYPT crypt() call performs decryption

3.1.3.2 enum modes

Modes of operation.

Enumerator:

ECB Electronic Code Book mode.CBC Cipher Block Chaining mode.CFB8 8-bit Cipher Feedback modeCFB64 64-bit Cipher Feedback modeCFB128 128-bit Cipher Feedback modeOFB Output Feedback mode.CTR Counter mode (NIST SP800-38A).

3.1.4 Constructor & Destructor Documentation

3.1.4.1 ∼AES () [inline]

Destructor. Calls clear().

Remarks:

Modifies: rk, iv, ctr are zeroized; algorithm state is set to UNINIT.

3.1.5 Member Function Documentation

3.1.5.1 void clear (void)

Clear the AES object.

Remarks:

Modifies: rk, iv, and ctr are zeroized; state is set to UNINIT.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 39: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.1 AES Class Reference 33

3.1.5.2 int crypt (int bytes, const char ∗ inbuf, char ∗ outbuf)

Encrypt or decrypt a specified buffer.

Parameters:

bytes length of input and output buffers; must be a multiple of 16 for ECB, CBC,OFB, CFB128, and CTR modes; a multple of 8 for CFB64; arbitrary forCFB8.

inbuf pointer to input buffer to be encrypted or decrypted

outbuf pointer to output buffer; output and input buffers may coincide.

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTRCDK_INVALID_DATA_LENGTHCDK_MODE_UNSUPPORTEDCDK_INVALID_MODE

Remarks:

Modifies: iv; to guard against reuse, ctr is auto-incremented.

3.1.5.3 int init (enum dirs dir, int keybytes, const char ∗ key, enum modes md =ECB, const char ∗ IV = 0)

Initialize the AES object.

Parameters:

dir a direction indicator: ENCRYPT or DECRYPT.

keybytes the length of key in bytes; 16, 24, or 32 for 128-, 192-, or 256-bit AESrespectively.

key a pointer to a buffer containing the key

md a mode indicator: ECB, CBC, CFB8, CFB64, CFB128, or OFB.

IV an 16-byte initialization vector (if required). If dir = ENCRYPT and md =CBC or CFB, the IV should be "unpredictable." If dir = ENCRYPT and md= OFB, the IV should be unique for each session. See NIST Spec. Pub.800-38a.

Returns:

0 (success)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 40: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

34 Data Structure Documentation

CDK_ERROR_STATECDK_OP_UNSUPPORTEDCDK_INVALID_MODECDK_INVALID_KEY_SIZECDK_MODE_UNSUPPORTEDCDK_INVALID_BLOCK_SIZECDK_INVALID_ROUNDSCDK_INVALID_KEY_PTR

Remarks:

Modifies: rk, direction, md, iv, KC, BC, ROUNDS, state (i.e., the AES object isgiven the specified direction, key, mode, and IV).

3.1.5.4 int setcounter (int bytes, const char ∗ counter)

Set counter for CTR mode.

Parameters:

bytes length of counter in bytes (must be 16).

counter pointer to buffer containing 16-byte counter value.

Returns:

0 (success)CDK_INVALID_DATA_LENGTHCDK_INVALID_PTR

Remarks:

Modifies: ctr

The documentation for this class was generated from the following file:

• aes.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 41: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.2 Algorithm Class Reference 35

3.2 Algorithm Class Reference

#include <alg.h>

Inheritance diagram for Algorithm:

Algorithm

AES

CRC

DES

EES

Key

MD2

MD5

Password

PRNG

RC2

RC4

RSA

SHA

SHA2

3.2.1 Detailed Description

Base class for tracking algorithm errors and internal system states.

Usage notes:Use Algorithm::isErrorState() to determine if the CDK is in the hard error state

i.e., if a crypto function has failed by returning a null or empty string.Use Algorithm::SetErrorState() to place the CDK into the hard error state.

This method is used internally and is unlikely to be called by an application.

Recommendations for strict FIPS 140-1 compliance:All methods may be used by a FIPS 140-1 compliant application. There are

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 42: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

36 Data Structure Documentation

no restrictions regarding the methods and functions defined in this file.

Public Types

• UNINIT = -1uninitialized

• INIT = 0initialized

• FINAL = 1final

• enum STATE {

UNINIT = -1,

INIT = 0,

FINAL = 1 }Algorithm states.

Public Member Functions

• Algorithm ()Constructor.

• virtual ∼Algorithm ()Destructor.

• void SetState (enum STATE st)Set this algorithm’s state indicator.

• int GetState (void) constGet this algorithm’s state indicator.

Static Public Member Functions

• static int isErrorState ()Predicate used to test the internal error state indicator.

• static void SetErrorState (char ∗lpszMessage=0)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 43: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.2 Algorithm Class Reference 37

Set internal error state indicator to true.

3.2.2 Member Enumeration Documentation

3.2.2.1 enum STATE

Algorithm states.

Enumerator:

UNINIT uninitialized

INIT initialized

FINAL final

3.2.3 Constructor & Destructor Documentation

3.2.3.1 Algorithm ()

Constructor.

Remarks:

Sets algorithm state indicator to UNIINIT.

3.2.4 Member Function Documentation

3.2.4.1 int GetState (void) const

Get this algorithm’s state indicator.

Returns:

the current algorithm state: UNINIT, INIT, or FINAL.

Remarks:

For internal use only. This function should not be called by an application.

3.2.4.2 static int isErrorState () [static]

Predicate used to test the internal error state indicator.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 44: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

38 Data Structure Documentation

Returns:

true, if the CDK is in the hard error statefalse, if the CDK is not in the hard error state

3.2.4.3 static void SetErrorState (char ∗ lpszMessage = 0) [static]

Set internal error state indicator to true.

Parameters:

lpszMessage pointer to associated error message

Remarks:

For internal use only. This function should not be called by an application.

3.2.4.4 void SetState (enum STATE st)

Set this algorithm’s state indicator.

Parameters:

st the new algorithm state: UNINIT, INIT, or FINAL.

Remarks:

For internal use only. This function should not be called by an application.

The documentation for this class was generated from the following file:

• alg.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 45: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.3 asn Struct Reference 39

3.3 asn Struct Reference

#include <asn.h>

Inheritance diagram for asn:

asn

str

Collaboration diagram for asn:

asn

str

3.3.1 Detailed Description

Internal data type used for ASN.1 BER/DER encoding/decoding.

Public Member Functions

Constructors

• asn ()Constructor for an empty object.

• asn (const asn &x)Copy constructor.

• asn (const str &x)Constructor based on a cdk::str object.

• asn (tags tag, const str &x, double extra)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 46: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

40 Data Structure Documentation

Constructor based on tag and body (allowing additional space for additions).

Assignment and Concatenation Operators

• asn operator= (const str &x)Assign a string to this object.

• asn operator= (const asn &x)Assign another asn object to this one.

• asn operator+= (const str &x)Concatenate a str object onto this one.

Predicates

• bool isParseable () constPredicate used to detect if object can be parsed as a sequence of ANS.1 records.

Inspectors

• int parseoid (int &alg, int &hashtype) constParse this object for an algorithm ID and hash function type.

Conversions

• asn tobin () constDecode object, converting base-64 encoded data to binary if necessary.

• str getText () constDecode object, converting text from Unicode to UTF8 if necessary.

• str dump (int level) constConvert object to a printable string for display purposes.

Static Public Member Functions

• static asn name (int code, const str &name)Encode a name as a UTF8String.

• static asn email (const str &address)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 47: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.3 asn Struct Reference 41

Encode an e-mail address as an IA5String.

• static asn date (TimeT t1)

Encode a UNIX date (chosing between UTCTime or GeneralizedTime to match input).

• static asn integer (int x)

Encode a small integer.

• static asn integer (const num &x)

Encode a num as an INTEGER.

• static asn Int_ (int &x, tags t=Int)

Encode a small integer or boolean value.

• static asn Date_ (TimeT &x)

Encode a date.

3.3.2 Member Function Documentation

3.3.2.1 static asn date (TimeT t1) [static]

Encode a UNIX date (chosing between UTCTime or GeneralizedTime to match input).

Parameters:

t1 the UNIX date to be encoded

Returns:

an object containing the encoded date

3.3.2.2 static asn Date_ (TimeT & x) [static]

Encode a date.

Parameters:

x the value to be encoded

Returns:

an object containing the input value in GeneralizedTime format

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 48: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

42 Data Structure Documentation

3.3.2.3 str dump (int level) const

Convert object to a printable string for display purposes.

Parameters:

level the number of levels to recurse into the ASN.1 record

Returns:

a cdk::str containing a printable representation of contents of this object

3.3.2.4 static asn email (const str & address) [static]

Encode an e-mail address as an IA5String.

Parameters:

address the address to be encoded

Returns:

an object containing the encoded e-mail address

3.3.2.5 str getText () const

Decode object, converting text from Unicode to UTF8 if necessary.

Returns:

a cdk::str representation of the text contained in this object

3.3.2.6 static asn Int_ (int & x, tags t = Int) [static]

Encode a small integer or boolean value.

Parameters:

x the value to be encoded

t the desired tag (defaults to INTEGER)

Returns:

an object containing the tagged input value as a variable-length integer

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 49: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.3 asn Struct Reference 43

3.3.2.7 static asn integer (const num & x) [inline, static]

Encode a num as an INTEGER.

Parameters:

x the value to be encoded

Returns:

an object containing the DER-encoded integer

3.3.2.8 static asn integer (int x) [static]

Encode a small integer.

Parameters:

x the value to be encoded

Returns:

an object containing the the DER-encoded integer

3.3.2.9 static asn name (int code, const str & name) [static]

Encode a name as a UTF8String.

Parameters:

code the name to be encoded

name the name to be encoded

Returns:

an object containing the encoded name

3.3.2.10 asn operator+= (const str & x) [inline]

Concatenate a str object onto this one.

Parameters:

x the asn tring to be copied

Reimplemented from str.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 50: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

44 Data Structure Documentation

3.3.2.11 asn operator= (const asn & x) [inline]

Assign another asn object to this one.

Parameters:

x the asn tring to be copied

3.3.2.12 asn operator= (const str & x) [inline]

Assign a string to this object.

Parameters:

x the string to be copied into this object

Reimplemented from str.

3.3.2.13 int parseoid (int & alg, int & hashtype) const

Parse this object for an algorithm ID and hash function type.

Parameters:

alg output parameter to receive algorithm ID

hashtype output parameter to receive hash function ID

3.3.2.14 asn tobin () const

Decode object, converting base-64 encoded data to binary if necessary.

Returns:

a new asn object containing the base-64 decoded data

The documentation for this struct was generated from the following file:

• asn.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 51: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.4 Cert Struct Reference 45

3.4 Cert Struct Reference

#include <cert.h>

Collaboration diagram for Cert:

Cert

asn

extensionssubject_oid

issuerissuer_oidsubject

issuer_uidsubject_pubsubject_uid

str

num

serial

FParms

p

Parameters Nat

v

primeinvbc

3.4.1 Detailed Description

Data type used for encoding and decoding individual X.509 certificates.

Data members closely map to standard X.509v3 certifcate fields. See RFC 3280,section 4.1 for details.

Sample code illustrating the use of this class appears in the Cookbook section Process-ing X.509v3 Certificates and CRLs.

Public Types

• V1 = 0

= 0 (1988)

• V2 = 1

= 1 (1992)

• V3 = 2

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 52: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

46 Data Structure Documentation

= 2 (1994)

• digitalSignature = 0x80

= 0x80, sign things other than certificates and CRLs

• nonRepudiation = 0x40

= 0x40, verify digital signatures for non-repudiation

• keyEncipherment = 0x20

= 0x20, wrap symmetric keys for transport

• dataEncipherment = 0x10

= 0x10, encrypt data other than keys

• keyAgreement = 0x08

= 0x08, perform key agreement

• keyCertSign = 0x04

= 0x04, verify signatures on certificates

• crlSign = 0x02

= 0x02, verify signatures on CRLs

• encipherOnly = 0x01

= 0x01, only for key enciphering; undefined without keyAgreement

• decipherOnly = 0x80

= 0x80, only for key deciphering; undefined without keyAgreement

• errNone

no error (success)

• errExpired

certificate has expired

• errIssuerMismatch

found unexpected issuer

• errRevoked

certificate has been revoked

• errParse

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 53: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.4 Cert Struct Reference 47

cannot parse certificate

• errBadPasswordinvalid password

• enum {

V1 = 0,

V2 = 1,

V3 = 2 }X.509 certificate version numbers.

• enum KeyUsage {

digitalSignature = 0x80,

nonRepudiation = 0x40,

keyEncipherment = 0x20,

dataEncipherment = 0x10,

keyAgreement = 0x08,

keyCertSign = 0x04,

crlSign = 0x02,

encipherOnly = 0x01,

decipherOnly = 0x80 }Masks for bits in the keyUsage extension. (See RFC 3280, section 4.2.1.3, for sug-gested semantics. Hints are provided below).

• enum errors {

errNone,

errExpired,

errIssuerMismatch,

errRevoked,

errParse,

errBadPassword }Various internal error codes.

Public Member Functions

Object Reuse and Initilization

• void clear ()

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 54: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

48 Data Structure Documentation

Clear the Cert object.

• int load (const str &b)Load an ASN.1 DER-encoded certificate.

• int loadbody (const str &body)Load an ASN.1 DER-encoded certificate body.

Inspectors

• int getext (int k, asn &val, asn &val2) constGet extensions.

• str makebody () constGet an ASN.1 DER-encoded tbsCertificate body.

Predicates

• bool isCA () constPredicate to test whether the certificate is that of a CA.

• int isExpired () constPredicate to test whether the certificate has expired.

Data Fields

• int versionversion number

• num serialcertificate serial number

• asn issuer_oidissuer signature algorithm identifier

• asn issuerissuer distinguished name

• TimeT notBeforestart of validity period

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 55: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.4 Cert Struct Reference 49

• TimeT notAfterend of validity period

• asn subjectsubject distinguished name

• asn subject_oidsubject key type identifier

• asn subject_pubsubject public key info; zeroized by str::∼str()

• asn issuer_uidissuer unique ID

• asn subject_uidsubject unique ID

• asn extensionsextensions

3.4.2 Member Enumeration Documentation

3.4.2.1 anonymous enum

X.509 certificate version numbers.

Enumerator:

V1 = 0 (1988)

V2 = 1 (1992)

V3 = 2 (1994)

3.4.2.2 enum errors

Various internal error codes.

Enumerator:

errNone no error (success)

errExpired certificate has expired

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 56: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

50 Data Structure Documentation

errIssuerMismatch found unexpected issuer

errRevoked certificate has been revoked

errParse cannot parse certificate

errBadPassword invalid password

3.4.2.3 enum KeyUsage

Masks for bits in the keyUsage extension. (See RFC 3280, section 4.2.1.3, for sug-gested semantics. Hints are provided below).

Enumerator:

digitalSignature = 0x80, sign things other than certificates and CRLs

nonRepudiation = 0x40, verify digital signatures for non-repudiation

keyEncipherment = 0x20, wrap symmetric keys for transport

dataEncipherment = 0x10, encrypt data other than keys

keyAgreement = 0x08, perform key agreement

keyCertSign = 0x04, verify signatures on certificates

crlSign = 0x02, verify signatures on CRLs

encipherOnly = 0x01, only for key enciphering; undefined without key-Agreement

decipherOnly = 0x80, only for key deciphering; undefined without key-Agreement

3.4.3 Member Function Documentation

3.4.3.1 int getext (int k, asn & val, asn & val2) const

Get extensions.

Parameters:

k index of certificate extension to retrieve (0, 1, etc. for first extension, secondextension, etc.)

val output buffer to receive OID of the k-th extension

val2 output buffer to receive the value of the k-th extension

Returns:

0 (success)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 57: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.4 Cert Struct Reference 51

CDK_EXTENSION_CRITICAL if the kth extension is marked critical (also con-sidered a success)CDK_EXTENSION_EMPTY if there is no kth extensionCDK_EXTENSION_PARSE_ERROR if the kth extension can’t be parsed

Remarks:

Call this function within a for/while loop until it returns CDK_EXTENSION_-EMPTY to retrieve all extensions in order.

3.4.3.2 bool isCA () const

Predicate to test whether the certificate is that of a CA.

Returns:

true if the certificate is self-signed or contains a basicConstraints extension indi-cating that the certificate is a CA certificatefalse otherwise

3.4.3.3 int isExpired () const

Predicate to test whether the certificate has expired.

Returns:

true if the current system date lies within the certificate’s validity periodfalse if the current system date lies outside the certificate’s validity period

3.4.3.4 int load (const str & b)

Load an ASN.1 DER-encoded certificate.

Parameters:

b an ASN.1 DER-encoded certificate.

Returns:

0 (success)CDK_CANT_PARSE_CERT

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 58: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

52 Data Structure Documentation

Remarks:

load() removes the issuer’s signature and passes the tbsCertificate body to load-body()Modifies: version, serial, issuer_oid, issuer, notBefore, notAfter, subject, subject_-oid subject_pub, issuer, issuer_oid, and extensions.

3.4.3.5 int loadbody (const str & body)

Load an ASN.1 DER-encoded certificate body.

Parameters:

body an ASN.1 DER-encoded tbsCertificate body (certificate without issuer’s sig-nature).

Returns:

0 (success)CDK_CANT_PARSE_CERT

Remarks:

Modifies: version, serial, issuer_oid, issuer, notBefore, notAfter, subject, subject_-oid subject_pub, issuer, issuer_oid, and extensions.

3.4.3.6 str makebody () const

Get an ASN.1 DER-encoded tbsCertificate body.

Returns:

an ASN.1 DER-encoded str containing the tbsCertificate body (i.e., the certificatebody to be signed consisting of: subject DN, subject oid, subject public key, valid-ity period, issuer DN, issuer oid, serial number, vesion, and extensions, but ∗not∗the issuer’s signature).

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 59: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.5 certid Struct Reference 53

3.5 certid Struct Reference

#include <cert.h>

Collaboration diagram for certid:

certid

str

serialissuer

3.5.1 Detailed Description

Data type used to detect matching certificates.

Public Member Functions

• int size () constGet the length in bytes of this object’s data.

• bool isMatch (const str &cer) constPredicate used to determine if the specified certificate wrapped the session key.

3.5.2 Member Function Documentation

3.5.2.1 bool isMatch (const str & cer) const

Predicate used to determine if the specified certificate wrapped the session key.

Parameters:

cer the certificate to match

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 60: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

54 Data Structure Documentation

3.6 Chain Struct Reference

#include <cert.h>

Collaboration diagram for Chain:

Chain

asn

certs

str

3.6.1 Detailed Description

Data type used for processing X.509 certificate chains.

Public Types

• root

= 0 (self-signed)

• user

= 1 (issuer and subject differ)

• enum certtype {

root,

user }

Certificate types.

Public Member Functions

Constructors

• Chain ()

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 61: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.6 Chain Struct Reference 55

Constructor used to create an empty object.

• Chain (const str &x)Constructor used to load an array of certificates into a new object.

Object Reuse and Initialization

• void clear ()Clear the Chain object, zeroizing all internal data members.

• void add (const str &cer)Append the specified certificate to the chain.

Inspectors

• int count () constCount certificates in the chain.

• str index (int k) constGet the kth certificate in the chain.

Search and Sort

• int find (certtype flag) constLocate a root or end-user certificate in the chain.

• int find (const str &cer, certtype flag) constLocate the parent or child of a given certificate in the chain.

• int findmatch (const str &infolist, asn &info, asn &cert) constSelect from a list of CMS RecipientInfo or SignerInfo PDUs the one matching aspecified certificate.

• int sort ()Sort the chain in descending order and prune it.

3.6.2 Member Enumeration Documentation

3.6.2.1 enum certtype

Certificate types.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 62: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

56 Data Structure Documentation

Enumerator:

root = 0 (self-signed)user = 1 (issuer and subject differ)

3.6.3 Constructor & Destructor Documentation

3.6.3.1 Chain (const str & x) [inline, explicit]

Constructor used to load an array of certificates into a new object.

Parameters:

x a list of binary, ASN.1 DER-encoded certificates simply concatentated together.

Remarks:

Modifies: certs

3.6.4 Member Function Documentation

3.6.4.1 void add (const str & cer) [inline]

Append the specified certificate to the chain.

Parameters:

cer a str containing the binary, ASN.1 DER-encoded certificate that is to be ap-pended to the chain

3.6.4.2 int count () const

Count certificates in the chain.

Returns:

the number of certificates found in the chain.

3.6.4.3 int find (const str & cer, certtype flag) const

Locate the parent or child of a given certificate in the chain.

Parameters:

cer certificate whose parent or child is requested

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 63: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.6 Chain Struct Reference 57

flag 0 (or root) to find parent, 1 (or user) to find child

Returns:

the index (>= 0) of the requested certificate-1 if the requested certificate cannot be found in the chain.

3.6.4.4 int find (certtype flag) const

Locate a root or end-user certificate in the chain.

Parameters:

flag 0 (or root) to find a self-signed certificate, 1 (or user) for an end-user certifi-cate (i.e., a certificate whose subject DN does not appear as the issuer DNelsewhere in the chain).

Returns:

the index (>= 0) of the requested certificate-1 if the requested certificate cannot be found in the chain.

3.6.4.5 int findmatch (const str & infolist, asn & info, asn & cert) const

Select from a list of CMS RecipientInfo or SignerInfo PDUs the one matching a spec-ified certificate.

Parameters:

infolist an array of PKCS #7 RecipientInfo or SignerInfo PDUs

info a pointer to the buffer that is to receive the matching RecipientInfo or Signer-Info PDU

cert the certificate to be matched in infolist.

Returns:

0 (success)2 if cert does not appear in infolist

3.6.4.6 str index (int k) const

Get the kth certificate in the chain.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 64: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

58 Data Structure Documentation

Parameters:

k index of the certificate to return.

Returns:

a str containing the kth certificate in the chain. (If the kth certificate doesn’t existor can’t be found, the str has zero length.)

3.6.4.7 int sort ()

Sort the chain in descending order and prune it.

Returns:

the number of discarded certificates

Remarks:

After execution the Chain object contains certificates sorted in top-down orderwith the root first and end-user certificate last. Certificates that are not part of thechain are discarded.

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 65: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.7 CMS1 Struct Reference 59

3.7 CMS1 Struct Reference

#include <cert.h>

Collaboration diagram for CMS1:

CMS1

asn

signersoidhash

crlsoidcipherrecip_cer

datarecips

Chain

certs

str

chn

3.7.1 Detailed Description

Data type used for in-memory PKCS #7 operations (RFC 3852 CMS).

Sample code illustrating the use of this class appears in the Cookbook section IETFCryptographic Message Syntax (CMS).

Public Member Functions

Object Reuse and Initialization

• void clear ()Clear this object.

• int load (const str &b)Load a CMS PDU into this object.

Predicates

• bool isEnveloped () const

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 66: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

60 Data Structure Documentation

Predicate used to determine whether this object contains a CMS EnvelopedDataPDU (i.e., is encrypted).

Encryption and Decryption

• int encrypt (const str &session, const str &iv, const str &msg, int ncipher=0)Encrypt specified data with this object and specified session key.

• int decrypt (const str &recip, const str &oid, const str &prv)Decrypt the contents of this object using a specified private key.

• int decrypt (const str &recip, const str &oid, tokenop &t1)Decrypt the contents of this object using the supplied callback function.

Inspectors

• str make () constCreate an ASN.1 DER-encoded PDU representing this object.

3.7.2 Member Function Documentation

3.7.2.1 int decrypt (const str & recip, const str & oid, tokenop & t1)

Decrypt the contents of this object using the supplied callback function.

Parameters:

recip the recipient’s certificate

oid an OID specifying the type of the recipient’s private key (required only ift1.privatekey is used; not required if callback used).

t1 a properly filled out tokenop structure for decrypt operations.

Returns:

0 (success) or nonzero (failure)

Remarks:

Only the first recipient of the EnvelopedData PDU is matched by this function.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 67: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.7 CMS1 Struct Reference 61

3.7.2.2 int decrypt (const str & recip, const str & oid, const str & prv)

Decrypt the contents of this object using a specified private key.

Parameters:

recip the recipient’s certificate

oid an OID specifying the type of the recipient’s private key

prv the recipient’s private key

Returns:

0 (success) or nonzero (failure)

Remarks:

Only the first recipient of the EnvelopedData PDU is matched by this function.

3.7.2.3 int encrypt (const str & session, const str & iv, const str & msg, intncipher = 0)

Encrypt specified data with this object and specified session key.

Parameters:

session the 24-byte TDES session key

iv the IV to use in CBC mode

msg the data to be encrypted

ncipher is the cipher to use 0 = TDES, 1 = AES (size based on key length)

Remarks:

This function produces the ingredients for an EnvelopedData PDU in several in-ternal buffers. You must call make() to obtain a string representation of the finalEnvelopedData PDU.

3.7.2.4 str make () const

Create an ASN.1 DER-encoded PDU representing this object.

Remarks:

This function takes the ingredients for an EnvelopedData or SignedData PDU fromits internal buffers and produces a string representation of the final CMS PDU.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 68: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

62 Data Structure Documentation

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 69: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.8 CRC Class Reference 63

3.8 CRC Class Reference

#include <crc.h>

Inheritance diagram for CRC:

CRC

Algorithm

Collaboration diagram for CRC:

CRC

Algorithm

3.8.1 Detailed Description

Implementation of the IEEE 32-bit CRC.

Usage flow:CRC() // construct CRC objectadd() // call as many times as necessary to process datafinal() // finalize computationsum() // obtain 32-bit CRC value

Recommendations for strict FIPS 140-1 compliance:CRC-32 is not a FIPS approved algorithm, so the CRC class should

*NOT* be used for cryptographic operations.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Message Digest Functions.

3.8.2 Technical Information and References

The generator polynomial used for this implementation is:

x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2

+ x + 1

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 70: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

64 Data Structure Documentation

as specified in the following standards: Autodin II, IEEE 802.3 (Ethernet), ISO/IEC-3309 (HDLC), RFC 1662 (PPP), and RFC 1952 (GZIP).

Public Member Functions

• CRC (int v=1)

Constructor.

• ∼CRC ()

Destructor. Calls clear().

• void add (int count, const char ∗s)

Update CRC with contents of buffer.

• void add (char c)

Update CRC with a single byte.

• void final (void)

Perform final masking operation.

• unsigned int sum () const

Get final CRC value.

• int length () const

Get size of CRC value in bytes.

• template<class T> T to () const

Convert 32-bit CRC value to type T.

• str tostr () const

Convert 32-bit CRC value to a str.

• void clear (void)

Clear CRC object.

• void reset (void)

Reset CRC object. Alias for clear().

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 71: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.8 CRC Class Reference 65

3.8.3 Constructor & Destructor Documentation

3.8.3.1 CRC (int v = 1) [inline]

Constructor.

Parameters:

v unused, but facilitates the use of templates.

Remarks:

Modifies: a = mask, byte count = 0; i.e., the object is reset to its initial state.

3.8.4 Member Function Documentation

3.8.4.1 void add (char c) [inline]

Update CRC with a single byte.

Parameters:

c byte to include in the CRC value being computed

Remarks:

This call updates the internal CRC value.

3.8.4.2 void add (int count, const char ∗ s)

Update CRC with contents of buffer.

Parameters:

count length of input buffer in bytes

s pointer to input buffer

Remarks:

This call updates the internal CRC value.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 72: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

66 Data Structure Documentation

3.8.4.3 void clear (void) [inline]

Clear CRC object.

Remarks:

Modifies: a = mask, byte count = 0; i.e., the object is reset to its initial state.

3.8.4.4 void final (void) [inline]

Perform final masking operation.

Remarks:

CRC value is updated by xoring with the mask.

3.8.4.5 void reset (void) [inline]

Reset CRC object. Alias for clear().

Remarks:

Modifies: a = mask, byte count = 0; i.e., the object is reset to its initial state.

3.8.4.6 unsigned int sum () const [inline]

Get final CRC value.

Returns:

the CRC value as an unsigned int.

3.8.4.7 T to () const [inline]

Convert 32-bit CRC value to type T.

Returns:

an object of type T representing the 32-bit CRC value.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 73: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.8 CRC Class Reference 67

3.8.4.8 str tostr () const

Convert 32-bit CRC value to a str.

Returns:

a str containing a string representation of the 32-bit CRC value.

The documentation for this class was generated from the following file:

• crc.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 74: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

68 Data Structure Documentation

3.9 CRL Struct Reference

#include <cert.h>

Collaboration diagram for CRL:

CRL

asn

bodyoid

issuersig

extralist

str

3.9.1 Detailed Description

Data type used for creating and processing certificate revocation lists.

Data members closely map to standard X.509v3 certifcate fields. See RFC 3280,section 5.1 for details.

Sample code illustrating the use of this class appears in the Cookbook section Process-ing X.509v3 Certificates and CRLs.

Public Types

• unspecified = 0unspecified

• keyCompromise = 1key compromise

• cACompromise = 2CA compromise.

• affiliationChanged = 3

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 75: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.9 CRL Struct Reference 69

affiliation changed

• superseded = 4superceded

• cessationOfOperation = 5cessation of operation

• certificateHold = 6certificate hold - see CRLInstructions

• removeFromCRL = 8remove from CRL

• privilegeWithdrawn = 9privilege withdrawn

• aACompromise = 10AA compromise.

• none = 1none

• callissuer = 2call issuer

• reject = 3reject

• pickuptoken = 4pickup token

• enum Reasons {

unspecified = 0,

keyCompromise = 1,

cACompromise = 2,

affiliationChanged = 3,

superseded = 4,

cessationOfOperation = 5,

certificateHold = 6,

removeFromCRL = 8,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 76: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

70 Data Structure Documentation

privilegeWithdrawn = 9,

aACompromise = 10 }CRL reason codes.

• enum Instructions {

none = 1,

callissuer = 2,

reject = 3,

pickuptoken = 4 }CRL instruction codes (use only with the certificateHold reason).

Public Member Functions

Object Reuse and Initialization

• void clear ()Clear this CRL object.

• int load (const str &b)Load a binary ASN.1 DER-encoded CRL into this object.

• void add (const num &serial, TimeT date)Add a certificate (and revocation date) to the CRL.

Validation

• int check (const str &certCA) constValidate the issuer’s digital signature on this CRL.

• int isRevoked (const str &cert, TimeT &date, int &reason) constTest whether a particular certificate has been revoked and, if so, get the revocationdate and reason code.

• int isExpired () constPredicate used to test whether this CRL has expired.

Inspectors

• str makebody () constGet an ASN.1 DER-encoded tbsCertList representing this CRL.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 77: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.9 CRL Struct Reference 71

Data Fields

• asn issuer

issuer distinguished name

• TimeT thisUpdate

date of this CRL

• TimeT nextUpdate

expected date of next CRL

• asn list

list of revoked serial numbers (revokedCertificates)

• int warn

warning flag

• asn body

CRL body.

• asn oid

algorithm ID

• asn sig

CRL signature.

3.9.2 Member Enumeration Documentation

3.9.2.1 enum Instructions

CRL instruction codes (use only with the certificateHold reason).

Enumerator:

none none

callissuer call issuer

reject reject

pickuptoken pickup token

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 78: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

72 Data Structure Documentation

3.9.2.2 enum Reasons

CRL reason codes.

Enumerator:

unspecified unspecified

keyCompromise key compromise

cACompromise CA compromise.

affiliationChanged affiliation changed

superseded superceded

cessationOfOperation cessation of operation

certificateHold certificate hold - see CRLInstructions

removeFromCRL remove from CRL

privilegeWithdrawn privilege withdrawn

aACompromise AA compromise.

3.9.3 Member Function Documentation

3.9.3.1 void add (const num & serial, TimeT date)

Add a certificate (and revocation date) to the CRL.

Parameters:

serial the serial number of the certificate to be added

date the revocationDate for this new CRL entry

Remarks:

Modifies: serial and date are ASN.1 encoded and appended to list.

3.9.3.2 int check (const str & certCA) const

Validate the issuer’s digital signature on this CRL.

Parameters:

certCA the binary ASN.1 DER-encoded certificate of the CRL issuer.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 79: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.9 CRL Struct Reference 73

Returns:

0 (success; the signature is valid)CDK_PARSE_ERROR (certCA or CRL can’t be parsed, or signature is invalid)CDK_CERT_EXPIRED (system time is outside the validity period of certCA)CDK_WRONG_ISSUER_CERT (certCA doesn’t match CRL issuer)

3.9.3.3 int isExpired () const

Predicate used to test whether this CRL has expired.

Returns:

true, if the system time lies outside this CRL’s validity periodfalse, if the system time lies within this CRL’s validity period

3.9.3.4 int isRevoked (const str & cert, TimeT & date, int & reason) const

Test whether a particular certificate has been revoked and, if so, get the revocation dateand reason code.

Parameters:

cert a binary ASN.1 DER-encoded certificate to be found in the CRL

date an output buffer for the revocationDate (if certificate is found)

reason an output buffer for the reason code (if certificate is found)

Returns:

0 (certificate is ∗not∗ in this CRLCDK_CERT_REVOKED (cert is in this CRL)CDK_PARSE_ERROR (cert or CRL can’t be parsed)CDK_CANT_PARSE_SUBJECT_CERT (cert body can’t be parsed)CDK_CRL_EXPIRED (system time lies outside validity period of this CRL)CDK_SUBJECT_CERT_EXPIRED (system time lies outside validity period ofcert)CDK_WRONG_ISSUER_CERT (cert issuer doesn’t match CRL issuer)

3.9.3.5 int load (const str & b)

Load a binary ASN.1 DER-encoded CRL into this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 80: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

74 Data Structure Documentation

Parameters:

b the binary ASN.1 DER-encoded CRL to be loaded

Returns:

0 (success)CDK_PARSE_ERROR, if the CRL can’t be parsed

Remarks:

Modifies: the CRL is parsed and Time, issuer, thisUpdate, nextUpdate, list, extra,warn, body, oid, and sig are filled in. warn = 2 if a CRL_deltaCRLIndicator wasfound in the CRL. warn = 3 if a CRL_issuingDistributionPoint was found in theCRL.

3.9.3.6 str makebody () const

Get an ASN.1 DER-encoded tbsCertList representing this CRL.

Returns:

a str containing an ASN.1 DER-encoded CRL body ready to be signed by its issuer(On error, the returned str has length 0: +str == 0.)

Remarks:

The str value returned by this function can be made into a signed, ASN.1 DER-encoded CRL by using Key::Sign and makesign().

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 81: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.10 Date Struct Reference 75

3.10 Date Struct Reference

#include <asn.h>

3.10.1 Detailed Description

Data type used for date and time processing.

Public Member Functions

Initialization

• void loadunix (double t1)Load object with double in standard UNIX format.

Conversions

• double tounix () constConvert object to standard UNIX format as a double.

• str tostr () constConvert Date object to a cdk::str object.

Data Fields

• int month

an integer in the range 1 – 12

• int day

an integer in the range 1 –31

• int year

an integer in the range 1980 – 2030

• int hour

an integer in the range 0 – 23

• int minute

an integer in the range 0 – 59

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 82: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

76 Data Structure Documentation

• int secondan integer in the range 0 – 59

• int gmtoffsetoffset from GMT in hours (e.g., PDT = +7)

3.10.2 Member Function Documentation

3.10.2.1 void loadunix (double t1)

Load object with double in standard UNIX format.

Parameters:

t1 a double representing the Date to be loaded in standard UNIX format.

3.10.2.2 str tostr () const

Convert Date object to a cdk::str object.

Returns:

a str representation of the date.

3.10.2.3 double tounix () const

Convert object to standard UNIX format as a double.

Returns:

a double representing the contents of this Date object in standard UNIX format.

The documentation for this struct was generated from the following file:

• asn.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 83: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.11 DES Class Reference 77

3.11 DES Class Reference

#include <des.h>

Inheritance diagram for DES:

DES

Algorithm

Collaboration diagram for DES:

DES

Algorithm

3.11.1 Detailed Description

Implementation of the NIST Data Encryption Standard (DES, TDES, and variants),FIPS 46-3/81.

All DES variants are 8-byte block ciphers with key sizes ranging from 64 to 192 bits.

Buffers may be encrypted or decrypted "in place," i.e., in == out is allowed in crypt().

Usage flow:DES() // instantiate a new DES objectinit() // specify the direction, key, algorithm variant, mode, and IV (if required)crypt() // perform the encrypt or decrypt operation

Recommendations for strict FIPS 140-1 compliance:ALG_DESX and ALG_DES40 cannot be used.ALG_DES is deprecated by NIST and should only be used if backwards

compatibility with another application is required.CTR mode and setcounter() should only be used with TDES.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Symmetric Ciphers.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 84: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

78 Data Structure Documentation

3.11.2 References

DES and TDES are specified in FIPS 46-3. Their modes of operation are specifiedin FIPS 81, NIST SP 800-20, and SP800-38A.

Public Types

• ENCRYPT

crypt() call performs encryption

• DECRYPT

crypt() call performs decryption

• NONE

DES object is uninitialized

• ALG_DES = 1

single DES; requires an 8-byte key

• ALG_DESX = 2

DESX; requires a 24-byte key.

• ALG_TDES = 3

triple DES; requires a 16- or 24-byte key

• ALG_DES40 = 4

40-bit DES; not implemented

• ALG_CDMF = 5

IBM’s 40-bit DES; not supported due to patent restrictions.

• ECB = 1

Electronic Code Book mode.

• CBC = 2

Cipher Block Chaining mode.

• CFB8

8-bit Cipher Feedback mode

• CFB32

32-bit Cipher Feedback mode

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 85: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.11 DES Class Reference 79

• CFB64

64-bit Cipher Feedback mode

• OFB

Output Feedback mode.

• CTR

Counter mode (NIST SP800-38A).

• enum dirs {

ENCRYPT,

DECRYPT,

NONE }

Direction flags.

• enum variants {

ALG_DES = 1,

ALG_DESX = 2,

ALG_TDES = 3,

ALG_DES40 = 4,

ALG_CDMF = 5 }

Algorithm IDs for DES-based cipher variants.

• enum modes {

ECB = 1,

CBC = 2 ,

CFB8,

CFB32,

CFB64,

OFB,

CTR }

Modes of operation.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 86: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

80 Data Structure Documentation

Public Member Functions

• DES ()

Constructor.

• ∼DES ()

Destructor. Calls clear().

• int init (enum dirs dir, int keybytes, const char ∗key, enum variants var=ALG_-DES, enum modes md=ECB, const char ∗iv=0)

Initialize algorithm object.

• int setcounter (int bytes, const char ∗counter)

Set counter for CTR mode.

• int crypt (int bytes, const char ∗inbuf, char ∗outbuf)

Encrypt or decrypt a specified buffer.

• void clear ()

Clear the DES object.

• void reset (enum dirs dir)

Reset DES object with possible change in direction of operation, but use same key.

3.11.3 Member Enumeration Documentation

3.11.3.1 enum dirs

Direction flags.

Enumerator:

ENCRYPT crypt() call performs encryption

DECRYPT crypt() call performs decryption

NONE DES object is uninitialized

3.11.3.2 enum modes

Modes of operation.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 87: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.11 DES Class Reference 81

Enumerator:

ECB Electronic Code Book mode.

CBC Cipher Block Chaining mode.

CFB8 8-bit Cipher Feedback mode

CFB32 32-bit Cipher Feedback mode

CFB64 64-bit Cipher Feedback mode

OFB Output Feedback mode.

CTR Counter mode (NIST SP800-38A).

3.11.3.3 enum variants

Algorithm IDs for DES-based cipher variants.

Enumerator:

ALG_DES single DES; requires an 8-byte key

ALG_DESX DESX; requires a 24-byte key.

ALG_TDES triple DES; requires a 16- or 24-byte key

ALG_DES40 40-bit DES; not implemented

ALG_CDMF IBM’s 40-bit DES; not supported due to patent restrictions.

3.11.4 Constructor & Destructor Documentation

3.11.4.1 DES () [inline]

Constructor.

Remarks:

Modifies: dir, var.

3.11.4.2 ∼DES () [inline]

Destructor. Calls clear().

Remarks:

Modifies: dir, var, k1, k2, k3, iv, sk1, sk2, sk3, state (keys and iv are zeroized).

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 88: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

82 Data Structure Documentation

3.11.5 Member Function Documentation

3.11.5.1 void clear ()

Clear the DES object.

Remarks:

Modifies: dir, var, k1, k2, k3, iv, sk1, sk2, sk3, state; keys and iv are zeroized.

3.11.5.2 int crypt (int bytes, const char ∗ inbuf, char ∗ outbuf)

Encrypt or decrypt a specified buffer.

Parameters:

bytes length of input and output buffers; must be a multiple of 8 for ECB, CBC,OFB, CFB64, and CTR modes; a multiple of 4 for CFB32; arbitrary forCFB8.

inbuf pointer to input buffer to be encrypted or decrypted

outbuf pointer to output buffer; output and input buffers may coincide

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTRCDK_INVALID_DATA_LENGTHCDK_MODE_UNSUPPORTEDCDK_INVALID_MODE

Remarks:

Modifies: iv; to guard against reuse, ctr is auto-incremented.

3.11.5.3 int init (enum dirs dir, int keybytes, const char ∗ key, enum variants var= ALG_DES, enum modes md = ECB, const char ∗ iv = 0)

Initialize algorithm object.

Parameters:

dir a direction indicator: ENCRYPT or DECRYPT

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 89: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.11 DES Class Reference 83

keybytes the length of key in bytes: 8, 16, or 24 (in TDES mode an 8/16 byte keyis replicated to obtain 24 bytes)

key a pointer to a buffer containing the key

var an indicator of the desired DES variant: ALG_DES, ALG_DESX, ALG_-TDES

md a mode indicator: ECB, CBC, CFB8, CFB32, CFB64, or OFB

iv an 8-byte initialization vector (if required). If dir = ENCRYPT and md = CBCor CFB, the IV should be "unpredictable". If dir = ENCRYPT and md = OFB,the IV should be unique for each session. See NIST Spec. Pub. 800-38a.

Returns:

0 (success)CDK_ERROR_STATECDK_OP_UNSUPPORTEDCDK_INVALID_MODECDK_INVALID_KEY_SIZECDK_MODE_UNSUPPORTEDCDK_INVALID_BLOCK_SIZECDK_INVALID_ROUNDSCDK_INVALID_KEY_PTR

Remarks:

Modifies: dir, mode, var, k1, k2, k3, iv, sk1, sk2, sk3, state (i.e., the DES object iscompletely initialized).

3.11.5.4 void reset (enum dirs dir)

Reset DES object with possible change in direction of operation, but use same key.

Parameters:

dir direction indicator: ENCRYPT or DECRYPT

Remarks:

Modifies: sk1, sk2, sk3. The subkey schedule is recomputed for a directionchange. (This function allows the direction to change without requiring the keyto be reloaded.)

3.11.5.5 int setcounter (int bytes, const char ∗ counter)

Set counter for CTR mode.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 90: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

84 Data Structure Documentation

Parameters:

bytes the length of the counter in bytes (must be 8)

counter a pointer to a buffer containing the 8-byte counter value

Returns:

0 (success)CDK_INVALID_DATA_LENGTHCDK_INVALID_PTR

Remarks:

Modifies: ctr.

The documentation for this class was generated from the following file:

• des.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 91: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.12 DName Struct Reference 85

3.12 DName Struct Reference

#include <cert.h>

Collaboration diagram for DName:

DName

str

titleorgunitserialemail

orgunit2uid

cnamecitystateorg

country

3.12.1 Detailed Description

Data type used for representing and processing X.500 distinguished names.

Public Member Functions

• void clear ()

Clear the DName object.

• str toasn1 () const

Get an ASN.1 DER-encoded string representation of the DN.

Data Fields

• str country

country name

• str cname

common name

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 92: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

86 Data Structure Documentation

• str orgorganization name

• str orgunitorganizational unit name 1

• str orgunit2organizational unit name 2

• str titletitle

• str citylocality name

• str statestate or province name

• str uidunique ID

• str emaile-mail address (deprecated)

• str serialserial number

3.12.2 Member Function Documentation

3.12.2.1 void clear ()

Clear the DName object.

Remarks:

All data members are zeroized.

3.12.2.2 str toasn1 () const

Get an ASN.1 DER-encoded string representation of the DN.

Input: The data members to be ASN.1 encoded have been filled in.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 93: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.12 DName Struct Reference 87

Returns:

an ASN.1 DER-encoded representation of the DN.

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 94: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

88 Data Structure Documentation

3.13 EES Class Reference

#include <ees.h>

Inheritance diagram for EES:

EES

Algorithm

Collaboration diagram for EES:

EES

Algorithm

3.13.1 Detailed Description

Implementation of the NIST EES ("Skipjack"), FIPS 185.

EES is an 8-byte block cipher with a key size of 80 bits.

Buffers may be encrypted or decrypted "in place," i.e., in == out is allowed in crypt().

Usage flow:EES() // instantiate a new EES objectinit() // specify the direction, key, mode and IV (if required)setcounter() // only required in CTR modecrypt() // perform the encrypt or decrypt operation

Recommendations for strict FIPS 140-1 compliance:All supported modes of EES are FIPS compliant.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Symmetric Ciphers.

3.13.2 References

EES is specified in FIPS 185 and SKIPJACK and KEA AlgorithmSpecifications. Modes of operation are covered in SP800-38A.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 95: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.13 EES Class Reference 89

Public Types

• ENCRYPTcrypt() call performs encryption

• DECRYPTcrypt() call performs decryption

• ECB = 1Electronic Code Book mode.

• CBC = 2Cipher Block Chaining mode.

• CFB88-bit Cipher Feedback mode

• CFB3232-bit Cipher Feedback mode

• CFB6464-bit Cipher Feedback mode

• OFBOutput Feedback mode.

• CTRCounter mode (NIST SP800-38A).

• enum dirs {

ENCRYPT,

DECRYPT }Direction flags.

• enum modes {

ECB = 1,

CBC = 2 ,

CFB8,

CFB32,

CFB64,

OFB,

CTR }

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 96: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

90 Data Structure Documentation

Modes of operation.

Public Member Functions

• ∼EES ()

Destructor. Calls clear().

• int init (enum dirs dir, int keybytes, const char ∗key, enum modes md=ECB,const char ∗IV=0)

Initialize algorithm object.

• int setcounter (int bytes, const char ∗counter)

Set counter for CTR mode.

• int crypt (int bytes, const char ∗inbuf, char ∗outbuf)

Encrypt or decrypt a specified buffer.

• void clear (void)

Clear the EES object.

3.13.3 Member Enumeration Documentation

3.13.3.1 enum dirs

Direction flags.

Enumerator:

ENCRYPT crypt() call performs encryption

DECRYPT crypt() call performs decryption

3.13.3.2 enum modes

Modes of operation.

Enumerator:

ECB Electronic Code Book mode.

CBC Cipher Block Chaining mode.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 97: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.13 EES Class Reference 91

CFB8 8-bit Cipher Feedback mode

CFB32 32-bit Cipher Feedback mode

CFB64 64-bit Cipher Feedback mode

OFB Output Feedback mode.

CTR Counter mode (NIST SP800-38A).

3.13.4 Constructor & Destructor Documentation

3.13.4.1 ∼EES () [inline]

Destructor. Calls clear().

Remarks:

Modifies: key, iv, str are zeroized.

3.13.5 Member Function Documentation

3.13.5.1 void clear (void)

Clear the EES object.

Remarks:

Modifies: rk, iv, ctr are zeroized; algorithm state set to UNINIT.

3.13.5.2 int crypt (int bytes, const char ∗ inbuf, char ∗ outbuf)

Encrypt or decrypt a specified buffer.

Parameters:

bytes length of input and output buffers; must be a multiple of 8 for ECB, CBC,OFB, CFB64, and CTR modes; a multiple of 4 for CFB32; arbitrary forCFB8.

inbuf pointer to input buffer to be encrypted or decrypted

outbuf pointer to output buffer; output and input buffers may coincide.

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 98: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

92 Data Structure Documentation

CDK_INVALID_PTRCDK_INVALID_DATA_LENGTHCDK_MODE_UNSUPPORTEDCDK_INVALID_MODE

Remarks:

Modifies: iv; to guard against reuse, ctr is auto-incremented.

3.13.5.3 int init (enum dirs dir, int keybytes, const char ∗ key, enum modes md =ECB, const char ∗ IV = 0)

Initialize algorithm object.

Parameters:

dir a direction indicator: ENCRYPT or DECRYPT

keybytes the length of key in bytes (must be 10)

key a pointer to a buffer containing the key

md a mode indicator: ECB, CBC, CFB8, CFB32, CFB64, or OFB

IV an 8-byte initialization vector (if required). If dir = ENCRYPT and md = CBCor CFB, the IV should be "unpredictable". If dir = ENCRYPT and md = OFB,the IV should be unique for each session. See NIST Spec. Pub. 800-38a.

Returns:

0 (success)CDK_ERROR_STATECDK_OP_UNSUPPORTEDCDK_INVALID_MODECDK_INVALID_KEY_SIZECDK_MODE_UNSUPPORTEDCDK_INVALID_BLOCK_SIZECDK_INVALID_ROUNDSCDK_INVALID_KEY_PTR

Remarks:

Modifies: dir, mode, key, iv, ctr (i.e., the EES object is completely initialized).

3.13.5.4 int setcounter (int bytes, const char ∗ counter)

Set counter for CTR mode.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 99: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.13 EES Class Reference 93

Parameters:

bytes length of counter in bytes (must be 8).

counter pointer to buffer containing 8-byte counter value.

Returns:

0 (success)CDK_INVALID_DATA_LENGTHCDK_INVALID_PTR

Remarks:

Modifies: ctr.

The documentation for this class was generated from the following file:

• ees.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 100: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

94 Data Structure Documentation

3.14 FParms Class Reference

#include <pk.h>

Inheritance diagram for FParms:

FParms

Parameters

Collaboration diagram for FParms:

FParms

Parameters Nat

primeinvbc

3.14.1 Detailed Description

Data type used to specify arithmetic parameters for various rings and fields.

Public Types

• typedef const num & cnum

const reference to a num

Protected Types

• None

type not specified

• Natural = 1

natural numbers

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 101: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.14 FParms Class Reference 95

• Negativenegative integers

• Char2field of characteristic 2

• Modularring of integers or prime field of characteristic greater than 2

• enum Types {

None,

Natural = 1,

Negative,

Char2,

Modular }IDs for various parameter types.

Protected Member Functions

• FParms (int type=Natural, int len=1)Constructor.

• FParms (int n1, const num &p1)Constructor.

• ∼FParms ()Destructor.

• void init (int n, const num &inv1)Initialize this object.

3.14.2 Member Enumeration Documentation

3.14.2.1 enum Types [protected]

IDs for various parameter types.

Enumerator:

None type not specified

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 102: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

96 Data Structure Documentation

Natural natural numbers

Negative negative integers

Char2 field of characteristic 2

Modular ring of integers or prime field of characteristic greater than 2

The documentation for this class was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 103: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.15 GParms Class Reference 97

3.15 GParms Class Reference

#include <pk.h>

Inheritance diagram for GParms:

GParms

Parameters

Collaboration diagram for GParms:

GParms

Parameters

FParms

num

T2T3T4T5abT1

p

Nat

v

primeinvbc

3.15.1 Detailed Description

Data type used to specify arithmetic parameters for various groups, including ellipticcurves.

Private Member Functions

• GParms (const num &gg)

Constructor specifying a group generator.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 104: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

98 Data Structure Documentation

• GParms (const num &a, const num &b)

Constructor specifying the coefficients in the equation of an elliptic curve:in char p: y 2 = x 3 + a x + bin char 2: y 2 + x y = x 3 + a x 2 + b.

• bool isChar2 () const

Predicate used to determine if underlying field is of characteristic 2.

• bool discriminant () const

Predicate used to test whether discrimant is nonzero.

3.15.2 Constructor & Destructor Documentation

3.15.2.1 GParms (const num & a, const num & b) [explicit, private]

Constructor specifying the coefficients in the equation of an elliptic curve:

in char p: y 2 = x 3 + a x + b

in char 2: y 2 + x y = x 3 + a x 2 + b.

Parameters:

a the first coefficient

b the second coefficient

Returns:

0

3.15.3 Member Function Documentation

3.15.3.1 bool discriminant () const [private]

Predicate used to test whether discrimant is nonzero.

Returns:

true, if discriminant is nonzerofalse, if discriminant is 0

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 105: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.15 GParms Class Reference 99

3.15.3.2 bool isChar2 () const [inline, private]

Predicate used to determine if underlying field is of characteristic 2.

Returns:

true, if underlying field is of characteristic 2false, otherwise

The documentation for this class was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 106: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

100 Data Structure Documentation

3.16 GroupData Struct Reference

#include <parms.h>

3.16.1 Detailed Description

Data type used to store parameters for particular Abelian groups.

Public Member Functions

• int check () const

Check parameter generation if seeded, then perform a sanity check on this object.

• str oid () const

Get an ASN.1 DER-encoded OID for the group parameters.

Data Fields

• const char ∗ name• int deg• const char ∗ p• const char ∗ order• const char ∗ seed• const char ∗ a• const char ∗ b• const char ∗ Gx• const char ∗ Gy• int start• int genseed

3.16.2 Member Function Documentation

3.16.2.1 int check () const

Check parameter generation if seeded, then perform a sanity check on this object.

Returns:

0 (success)non-zero, on error

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 107: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.16 GroupData Struct Reference 101

Remarks:

See Key::loadoid(), Key::checkSeed(), Key::genpub(), Key::check() for specificerror codes.

3.16.2.2 str oid () const

Get an ASN.1 DER-encoded OID for the group parameters.

Returns:

a str containing an ASN.1 OID representing the parameters suitable for passing toKey::loadoid().

3.16.3 Field Documentation

3.16.3.1 const char∗ a

DSA: NULL

EC: first coefficient in curve’s defining polynomial

3.16.3.2 const char ∗ b

DSA: NULL

EC: second coefficient in curve’s defining polynomial

3.16.3.3 int deg

DSA: hash function ID (0=SHA, 1=SHA-1)

EC2: degree of field extension

ECP: 0

3.16.3.4 int genseed

((p-1)/q)-th power is the group generator (NIST examples use 2, ISC uses 7)

3.16.3.5 const char∗ Gx

DSA: subgroup generator g

EC: x-coordinate of base point

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 108: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

102 Data Structure Documentation

3.16.3.6 const char ∗ Gy

DSA: NULL

EC: y-coordinate of base point

3.16.3.7 const char∗ name

printable string describing these parameters

3.16.3.8 const char∗ order

DSA: q

EC: subgroup order (decimal or hex, if prefixed by "0x")

3.16.3.9 const char∗ p

prime modulus or irreducible polynomial (decimal or hex, if prefixed by "0x")

3.16.3.10 const char∗ seed

DSA/EC: NIST seed for pseudorandomly-generated parameters, otherwise an emptystring

3.16.3.11 int start

starting value of counter (DSA only)

The documentation for this struct was generated from the following file:

• parms.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 109: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.17 ISC_CDK Class Reference 103

3.17 ISC_CDK Class Reference

#include <cdk.h>

3.17.1 Detailed Description

Base class for FIPS 140-1 on-demand self-tests, error state tracking, and convenienceutilities.

All public symbols are in the ’cdk’ namespace, except for a few assembly languagefunctions under Windows.

Functions typically return 0 on success.

Usage flow:ISC_CDK() // instantiate a new ISC_CDK objectTest_XYZ() // run a specified level of as many on-demand tests as you requireSelfTest() // or run groups of selftests (e.g., test all symetric ciphers)isOK() // or run all self-tests in level 0

Recommendations for strict FIPS 140-1 compliance:All methods in this class may be used by a FIPS 140-1 compliant application.There are no restrictions regarding the functions defined in this file.

Notes:

• Level 0 execute only the first of the possible self-tests for each algorithm.

• Level 1 executes all self-tests for each algorithm, including any relevant MonteCarlo tests. For this reason, level 1 tests can take a considerable amount of timeto execute.

Primary Self-Test and Inspectors

• int SelfTest (int level=0, char options[ ]="a")

Run one or more system self-tests at the specified level.

• bool isOK ()

Predicate used to test the hard error state and run all self-tests at level 0.

• static int Version ()

Get the CDK version number.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 110: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

104 Data Structure Documentation

Public Member Functions

Constructor and Destructor

• ISC_CDK ()Constructor.

• virtual ∼ISC_CDK ()Destructor.

On-Demand Self-TestsAll of these functions are called by SelfTest().

• int Test_CRC (int level)Run the CRC-32 tests.

• int Test_MD2 (int level)Run the MD2 tests.

• int Test_MD5 (int level)Run the MD5 tests.

• int Test_SHA1 (int level)Run the SHA-1 tests.

• int Test_SHA256 (int level)Run the SHA-256 tests.

• int Test_SHA384 (int level)Run the SHA-384 tests.

• int Test_SHA512 (int level)Run the SHA-512 tests.

• int Test_HMAC (int level)Run the HMAC tests.

• int Test_DES (int level)Run the DES tests.

• int Test_TDES (int level)Run the TDES tests.

• int Test_AES (int level)Run the AES tests.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 111: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.17 ISC_CDK Class Reference 105

• int Test_AES_Modes (int level)Run the AES Modes tests.

• int Test_RC2 (int level)Run the RC2 tests.

• int Test_RC4 (int level)Run the RC4 tests.

• int Test_EES (int level)Run the EES tests.

• int Test_DSA (int level)Run the DSA tests.

• int Test_ECDSA (int level)Run the ECDSA tests for NIST curves over fields of characteristic p > 2.

• int Test_ECDSA2 (int level)Run the ECDSA tests for NIST curves over binary fields (characteristic 2).

• int Test_RSASign (int level)Run the RSA signature tests.

• int Test_PRNG (int level)Run the pseudorandom number generation tests.

• int Test_PKCS12 (int level)Run the PKCS#12 tests.

• int Test_PWD_Generator (int level)Test the CDK’s FIPS 181 password generator.

3.17.2 Member Function Documentation

3.17.2.1 bool isOK () [inline]

Predicate used to test the hard error state and run all self-tests at level 0.

Returns:

true (success), if all self-tests execute successfullyfalse, if any self-test fails or the CDK is already in its hard error state

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 112: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

106 Data Structure Documentation

3.17.2.2 int SelfTest (int level = 0, char options[ ] = "a")

Run one or more system self-tests at the specified level.

Parameters:

level the run level: 0 or 1

options a character string containing a combination of a, c, d, o and r

Returns:

0 (success), if all requested self-tests executed successfullyCDK_ERROR_STATE

Remarks:

The options string may consist of any combination of the following letters:

• a = run all tests.

• c = test symmetric ciphers (AES, DES, TDES, EES, RC2, RC4)

• d = test message digests (CRC, MD2/MD5,SHA1, SHA-256, -384, -512,HMAC-SHA1

• p = test public key algorithms (DSA, RSA, ECDSA)

• r = test PRNG thus "cd" would run both symmetric cipher self-tests and mes-sage digest self-test.

Calling SelfTest() with no parameters runs all tests at level 0.If a self-test fails, the CDK enters its hard error state and throws an assertion. Thisshould cause the calling application to exit.

3.17.2.3 int Test_AES (int level)

Run the AES tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 113: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.17 ISC_CDK Class Reference 107

3.17.2.4 int Test_AES_Modes (int level)

Run the AES Modes tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.5 int Test_CRC (int level)

Run the CRC-32 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.6 int Test_DES (int level)

Run the DES tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.7 int Test_DSA (int level)

Run the DSA tests.

Parameters:

level the run level: 0 or 1

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 114: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

108 Data Structure Documentation

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.8 int Test_ECDSA (int level)

Run the ECDSA tests for NIST curves over fields of characteristic p > 2.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.9 int Test_ECDSA2 (int level)

Run the ECDSA tests for NIST curves over binary fields (characteristic 2).

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.10 int Test_EES (int level)

Run the EES tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 115: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.17 ISC_CDK Class Reference 109

3.17.2.11 int Test_HMAC (int level)

Run the HMAC tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.12 int Test_MD2 (int level)

Run the MD2 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.13 int Test_MD5 (int level)

Run the MD5 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.14 int Test_PKCS12 (int level)

Run the PKCS#12 tests.

Parameters:

level the run level: 0 or 1

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 116: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

110 Data Structure Documentation

Returns:

0 (success)CDK_ERROR_STATE

Remarks:

This function tests the ability of the CDK to properly create keys from passwordsas per PKCS#12.

3.17.2.15 int Test_PRNG (int level)

Run the pseudorandom number generation tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.16 int Test_PWD_Generator (int level)

Test the CDK’s FIPS 181 password generator.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.17 int Test_RC2 (int level)

Run the RC2 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 117: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.17 ISC_CDK Class Reference 111

3.17.2.18 int Test_RC4 (int level)

Run the RC4 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.19 int Test_RSASign (int level)

Run the RSA signature tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.20 int Test_SHA1 (int level)

Run the SHA-1 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.21 int Test_SHA256 (int level)

Run the SHA-256 tests.

Parameters:

level the run level: 0 or 1

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 118: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

112 Data Structure Documentation

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.22 int Test_SHA384 (int level)

Run the SHA-384 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.23 int Test_SHA512 (int level)

Run the SHA-512 tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

3.17.2.24 int Test_TDES (int level)

Run the TDES tests.

Parameters:

level the run level: 0 or 1

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 119: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.17 ISC_CDK Class Reference 113

3.17.2.25 static int Version () [inline, static]

Get the CDK version number.

Returns:

a three digit decimal number that encodes the CDK version number

Remarks:

A return value of, say "701," represents Version 7.0.1.

The documentation for this class was generated from the following file:

• cdk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 120: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

114 Data Structure Documentation

3.18 Key Struct Reference

#include <pk.h>

Inheritance diagram for Key:

Key

Algorithm

Collaboration diagram for Key:

Key

Algorithm

RSA Point

pubgen

GParms

p

Parameters

FParms

num

priv

xyz

T 2T 3T4T5abT1

dmods1dmodr1

pqexpo

dmodq1qinvmodpdmodp1

pqinvmodrpqrsd

pqrinvmods

p

Nat

v

primeinvbc

str

keytypersai

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 121: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 115

3.18.1 Detailed Description

Class Key is the principal data type used for public and private keys and all relatedcryptographic operations.

3.18.2 Using Class Key

In this section we briefly document the most common uses of class Key. Additionalcode samples illustrating the use of this class can be found in the Cookbook sectionHandling Public and Private Keys.

3.18.2.1 Generating RSA Keys

To generate an RSA key pair, you typically instantiate a Key object and call RSAkey-gen() with a random seed (and possibly default parameter overrides). For example, togenerate a new 2048-bit RSA key pair with public exponent F4:

PRNG rand;Key key;key.RSAkeygen(rand.gens(64), 2048);

3.18.2.2 Generating DSA/DH/ECDSA/ECDH Keys

To generate a key pair for one of the discrete log-based schemes, you typically instan-tiate a Key object and call DLkeygen() with a random seed and your group parametersspecified by OID. For example, to generate a new 1024-bit DSA key based on the NISTFIPS 186-2 sample parameters:

PRNG rand;Key key;key.DLkeygen(rand.gens(20), DSA_Parms[0].oid()) );

3.18.2.3 Using Existing Key Pairs

Use the following pseudocode to load an existing key pair into a key object:

Key() // instantiate a Key objectloadoid() // specify key type and sizeloadprv() // load ASN.1 DER-encoded private key componentsloadpub() // load ASN.1 DER-encoded public key components

Important Note: Loading a private key clears the public key in the Key object if oneis present, so when loading a key pair, you should always load the private componentsfirst, then the public.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 122: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

116 Data Structure Documentation

Once generated or loaded, key components may be accessed using the followingmember functions: asn1parameters() // get ASN.1 DER-encoded parameters (if any)asn1private() // get ASN.1 DER-encoded private key asn1public() // get ASN.1 DER-encoded public key

3.18.2.4 Implementing Diffie-Hellman Key Agreement

Suppose that two parties, named Alice and Bob, wish to establish a common secret keyusing a insecure communications channel. (We’ll assume they have previously agreedupon group parameters with the ASN.1 DER-encoded object identifier strOID.)

PHASE I: Alice instantiates a Key object, privately generates her (static or ephemeral)key pair in the specified group, and extracts her public key:

PRNG rand;Key dhAlice;dhAlice.DLkeygen(rand.gens(20),strOID);str strAlicePK = dhAlice.asn1public();

while Bob privately does the same:

PRNG rand;Key dhBob;dhBob.DLkeygen(rand.gens(20),strOID);str strBobPK = dhBob.asn1public();

EXCHANGE: Alice and Bob now exchange their public keys over the insecure chan-nel. Allice sends strAlicePK to Bob, and Bob sends strBobPK to Alice. (Typically,Alice and Bob obtain certificates for their public keys from a trusted third party andmake those certificates available to each other by publishing them in a public reposi-tory.)

PHASE II: Alice now computes the common Diffie-Hellman secret by loading Bob’spublic key into a Key object and raising it to her private exponent (using the modularexponeniation function provided by Point::operator∗()).

Key Bob;Bob.loadoid(strOID);Bob.loadpub(strBobPK);Point DHsecret = Bob.pub * kAlice.getPrivate();

while Bob does a similar thing on his side:

Key Alice;Alice.loadoid(strOID);Alice.loadpub(strAlicePK);Point DHsecret = Alice.pub * kBob.getPrivate();

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 123: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 117

Now Alice and Bob both possess the (full) Diffie-Hellman secret and can apply a pre-viously agreed upon key derivation function to derive from it any type of (symmetric)key they desire.

See also: Diffie-Hellman Key Agreement in the Cookbook.

Public Types

• digitalSignature = 0x80= 0x80

• nonRepudiation = 0x40= 0x40

• keyEncipherment = 0x20= 0x20

• dataEncipherment = 0x10= 0x10

• keyAgreement = 0x08= 0x08

• keyCertSign = 0x04= 0x04

• crlSign = 0x02= 0x02

• encipherOnly = 0x01= 0x01

• usageAll = 0xFF= 0xFF

• enum {

digitalSignature = 0x80,

nonRepudiation = 0x40,

keyEncipherment = 0x20,

dataEncipherment = 0x10,

keyAgreement = 0x08,

keyCertSign = 0x04,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 124: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

118 Data Structure Documentation

crlSign = 0x02,

encipherOnly = 0x01,

usageAll = 0xFF }keyUsage bit masks

Public Member Functions

Constructor and Destructor

• Key ()Constructor.

• virtual ∼Key ()Destructor.

Object Reuse and Initialization

• void clear ()Clear this object.

• void settype (const str &kyp)Set this object’s key type and size.

• int setorder (const num &q)Set the order of this key’s underlying Abelian group.

• void setdefaulthash ()Set the hashtype of this object to SHA-1.

• int DLLoadPublic (const num &y)Load a (raw) DSA or ECDSA public key into this object.

• int setPrivate (const str &p)Load a (raw) DSA or ECDSA private key into this object.

• int RSALoadPublic (const num &expo1, const num &pq1)Load a raw RSA public key (exponent and modulus) into this object.

• void loadprivate (const num &x)Load a raw RSA private key (a single factor of the modulus) into this object.

• int genpub ()Generate a public key based on the private key components in this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 125: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 119

• int loadseed (const str &seed, int np, int &counter)Load DSA parameters based on a specified SEED.

• int loadoid (const str &oid)Load ASN.1 encoded parameters.

• int loadprv (const str &prv)Load an ASN.1 encoded private key (in the clear).

• int loadpub (const str &pubk)Load an ASN.1 encoded public key.

Inspectors

• str id () constGet an ASCII description of this object’s key type and size.

• int DLGetRawPublic (num &x, num &y) constGet the raw DL public key from this object.

• int RSAGetRawPublic (num &expo1, num &pq1)Get the raw RSA public key from this object.

• int GetRawPrivate (num &x)Get the raw DL private key from this object.

• int alg () constGet this key’s "type.".

• int bits () constGet the "size" of the key in this object.

• int rawsiglength () constGet the length in bytes of a raw signature associated with this key.

• num getPrivate () constGet the (raw) private key in this object.

• str asn1private () constGet the ASN.1 encoded private key in this object.

• str asn1public () constGet the ASN.1 encoded public key in this object.

• str asn1parameters (int full=1, int withhash=1) const

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 126: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

120 Data Structure Documentation

Get the ASN.1 encoded parameters in this Key object.

• num order () constGet the order of this key’s underlying Abelian group.

• num A () constGet the first coefficient in the equation for this object’s underlying elliptic curve.

• num B () constGet the second coefficient in the equation for this object’s underlying elliptic curve.

Sanity Checks

• int check () constCheck the consistency of the keypair in this object.

• int checkSeed (const str &seed, int start=0, int v=1, int h=2)Check that this object’s key parameters were correctly generated as per NIST FIPS186-2.

Key Generation

• int RSAkeygen (const str &seed, int nbits=1024, const num &expo-nent=65537, int factors=2)

Generate an RSA keypair.

• int DLkeygen (const str &seed, const str &strOID)Generate a DL keypair.

• int power (const num &a, num &x) constPerform modular exponentiation with this object’s private key (for DH or El-Gamal).

Encryption and Decryption

• int Encrypt (const str &a, str &x) constEncrypt (or wrap) a specified buffer using this object’s public key.

• int Encrypt (const str &a, const str &seed, str &x) constEncrypt (or wrap) a specified buffer using this object’s public key.

• int Decrypt (const str &a, str &x) constDecrypt (or unwrap) a specified buffer using this object’s private key.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 127: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 121

Signatures and Validation

• void SetPadding (int nPadding)Set the RSA padding scheme to use when signing.

• int Sign (const num &hash, const num &random, Signature &sig) constSign the specified message digest using this object’s private key.

• int asn1sign (const str &msg, const num &krand, str &sig) constProduce an ASN.1 DER-encoded signature over a specified message.

• int SignCheck (const num &hash, const Signature &sig) constCheck the validity of a specified signature against this object’s public key.

• int SignCheck (const num &hash, const str &sig) constCheck the validity of a specified signature against this object’s public key.

Useful Predicates

• bool hasPublic () constPredicate used to determine whether this object contains a public key.

• bool isRSA () constPredicate used to determine whether this object contains an RSA key.

• bool isDH () constPredicate used to determine whether this object contains an DH/DSA key.

• bool isEC () constPredicate used to determine whether this object contains an elliptic curve key.

• bool isChar2 () constPredicate used to test whether this object is an elliptic curve key over a field ofcharacteristic 2.

• bool permit (int flag) constPredicate used to test keyUsage bit settings.

Conversion Function

• template<class T> T to () constConvert this key object into an object of type T.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 128: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

122 Data Structure Documentation

Data Fields

• int usagekeyUsage extension

• str keytypekey type (e.g., gRSA, gDSA, gECP, or gEC2)

• int hashtypehash type (e.g., hSHA1)

• Point gengroup generator (base point)

• Point pubpublic key

• int cofactorcofactor (EC only)

• RSA rsaiRSA key components.

3.18.3 Member Enumeration Documentation

3.18.3.1 anonymous enum

keyUsage bit masks

Enumerator:

digitalSignature = 0x80

nonRepudiation = 0x40

keyEncipherment = 0x20

dataEncipherment = 0x10

keyAgreement = 0x08

keyCertSign = 0x04

crlSign = 0x02

encipherOnly = 0x01

usageAll = 0xFF

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 129: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 123

3.18.4 Constructor & Destructor Documentation

3.18.4.1 Key () [inline, explicit]

Constructor.

Remarks:

Modifies: hashtype = hSHA1, usage, m_nDoPWCC

3.18.4.2 virtual ∼Key () [inline, virtual]

Destructor.

Remarks:

All key components are stored in objects whose destructors zeroize them.

3.18.5 Member Function Documentation

3.18.5.1 num A () const [inline]

Get the first coefficient in the equation for this object’s underlying elliptic curve.

Returns:

the A coefficient of the equation for this object’s elliptic curve

Remarks:

Use this function only with ECC keys.

3.18.5.2 int alg () const

Get this key’s "type.".

Returns:

an algorithm identifier for the key type: gRSA, gDSA, gECP, or gEC2

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 130: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

124 Data Structure Documentation

3.18.5.3 str asn1parameters (int full = 1, int withhash = 1) const

Get the ASN.1 encoded parameters in this Key object.

Parameters:

full parameter indicator: 1 to include parameters, 0 to produce OID only

withhash digest indicator: 1 to include digest OID, 0 to omit digest OID

Returns:

a str containing the ASN.1 encoded parameters for this key object

3.18.5.4 str asn1private () const

Get the ASN.1 encoded private key in this object.

Returns:

a str containing an ASN.1 encoded representation of the private key in this object.

3.18.5.5 str asn1public () const

Get the ASN.1 encoded public key in this object.

Returns:

a str containing an ASN.1 encoded representation of the public key in this object.

3.18.5.6 int asn1sign (const str & msg, const num & krand, str & sig) const

Produce an ASN.1 DER-encoded signature over a specified message.

Parameters:

msg the message data to be hashed and signed

krand a random number (can be generated with num(gens(20))

sig the output buffer that is to receive the ASN.1 DER-encoded signature

Remarks:

This function can be used to produce an X.509v3 certificate (resp. CRL) by sup-plying a TBSCertificate (resp. TBSCertList) PDU as the actual msg parameter.After the call, sig will contain the desired X.509 certificate (resp. CRL).

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 131: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 125

Returns:

0 (success)CDK_ERROR_STATECDK_PRVKEY_CANNOT_FINDCDK_INVALID_KEYUSAGECDK_INTERNAL_ERRCDK_INVALID_SIGNATURE

3.18.5.7 num B () const [inline]

Get the second coefficient in the equation for this object’s underlying elliptic curve.

Returns:

the B coefficient of the equation for this object’s elliptic curve

Remarks:

Use this function only with ECC keys.

3.18.5.8 int bits () const [inline]

Get the "size" of the key in this object.

Returns:

the number of bits in the RSA modulus or DL generator

3.18.5.9 int check () const

Check the consistency of the keypair in this object.

Returns:

0, if key pair is OKCDK_KEYPAIR_INCONSISTENT

Remarks:

This function also performs appropriate sanity checks, such as primality testing,where appropriate.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 132: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

126 Data Structure Documentation

3.18.5.10 int checkSeed (const str & seed, int start = 0, int v = 1, int h = 2)

Check that this object’s key parameters were correctly generated as per NIST FIPS186-2.

Parameters:

seed the initial SEED value

start a starting value for the counter

v an algorithm indicator: for DSA, use v=0 for SHA, v=1 for SHA-1; for ECP,use v=0; for EC2, v should be the degree of extension field over Z2.

h the value used to obtain the generator (i.e., g = h∧[(p-1)/q]; for DSA only)

Returns:

0, if OKnon-zero otherwise

3.18.5.11 int Decrypt (const str & a, str & x) const

Decrypt (or unwrap) a specified buffer using this object’s private key.

Parameters:

a the input ciphertext buffer

x an output buffer for the plaintext

Returns:

0 (success)CDK_ERROR_STATECDK_PRVKEY_CANNOT_FINDCDK_KEY_INVALID_USAGE

3.18.5.12 int DLGetRawPublic (num & x, num & y) const

Get the raw DL public key from this object.

Parameters:

x an output buffer for the DSA/DH public key (or x coordinate of the EC publickey)

y an output buffer for the y coordinate of the EC public key (receives 0 in theDSA/DH case)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 133: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 127

Returns:

0 (success)CDK_INVALID_KEYTYPECDK_ERROR_STATE

3.18.5.13 int DLkeygen (const str & seed, const str & strOID)

Generate a DL keypair.

Parameters:

seed a random number (at least 20 bytes, preferably 40; can be generated withPRNG::gens(40))

strOID an ASN.1 DER-encoded OID specifying the DSA/ECDSA parameters tobe used.

Returns:

0 (success)CDK_ERROR_STATECDK_KEYPAIR_INCONSISTENT

3.18.5.14 int DLLoadPublic (const num & y)

Load a (raw) DSA or ECDSA public key into this object.

Parameters:

y the raw DL public key (private exponent) to be loaded

Returns:

0 (success)CDK_KEY_INVALID

3.18.5.15 int Encrypt (const str & a, const str & seed, str & x) const

Encrypt (or wrap) a specified buffer using this object’s public key.

Parameters:

a the input plaintext buffer

seed an input for pseudorandom number generation

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 134: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

128 Data Structure Documentation

x an output buffer for the ciphertext

Remarks:

This function performs a non-deterministic computation in when see is random.This means that the output is only reproducable if the seed is the same in eachcase.

Returns:

0 (success)CDK_ERROR_STATECDK_KEY_INVALID_USAGE

3.18.5.16 int Encrypt (const str & a, str & x) const

Encrypt (or wrap) a specified buffer using this object’s public key.

Parameters:

a the input plaintext bufferx an output buffer for the ciphertext

Remarks:

This function performs a deterministic computation in all cases. This means thatthe output is reproducable for the same input.

Returns:

0 (success)CDK_ERROR_STATECDK_KEY_INVALID_USAGE

3.18.5.17 int genpub ()

Generate a public key based on the private key components in this object.

Remarks:

genpub() calls pairwise consistency checks required for FIPS 140-1 compliance.

Returns:

0 (success)CDK_ERROR_STATECDK_KEYPAIR_INCONSISTENT

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 135: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 129

3.18.5.18 num getPrivate () const [inline]

Get the (raw) private key in this object.

Returns:

this object’s private key

3.18.5.19 int GetRawPrivate (num & x)

Get the raw DL private key from this object.

Parameters:

x an buffer for the private key

Returns:

0 (success) CDK_ERROR_STATE

3.18.5.20 bool hasPublic () const [inline]

Predicate used to determine whether this object contains a public key.

Returns:

true, if this object contains a public keyfalse otherwise

3.18.5.21 str id () const

Get an ASCII description of this object’s key type and size.

Returns:

an ASCII description of the key and its size (e.g., "RSA-1024", "EC2-163", etc.)

3.18.5.22 bool isChar2 () const [inline]

Predicate used to test whether this object is an elliptic curve key over a field of charac-teristic 2.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 136: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

130 Data Structure Documentation

Returns:

true, if this object is an elliptic curve key over a field of char 2false otherwise

3.18.5.23 bool isDH () const [inline]

Predicate used to determine whether this object contains an DH/DSA key.

Returns:

true, if this object contains a DH/DSA keyfalse otherwise

3.18.5.24 bool isEC () const [inline]

Predicate used to determine whether this object contains an elliptic curve key.

Returns:

true, if this object contains an elliptic curve keyfalse otherwise

3.18.5.25 bool isRSA () const [inline]

Predicate used to determine whether this object contains an RSA key.

Returns:

true, if this object contains an RSA keyfalse, otherwise

3.18.5.26 int loadoid (const str & oid)

Load ASN.1 encoded parameters.

Parameters:

oid a str containing an ASN.1 encoded OID providing RSA/DSA/ECDSA param-eters Modifies: hashtype, rsai, cofactor, priv, gen, pub

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 137: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 131

Returns:

0 (success)2, 23 = parse error3 = DSA parse error4, 26 = unknown/unsupported alg22 = ECDSA parse error

3.18.5.27 void loadprivate (const num & x)

Load a raw RSA private key (a single factor of the modulus) into this object.

Parameters:

x the raw private key to be loaded

Remarks:

Modifies: rsai, priv, pub is cleared or rsai.pq is cleared

Note:

To load a raw RSA private key do the following:Key k;k.rsai.loadpriv(p,q);

3.18.5.28 int loadprv (const str & prv)

Load an ASN.1 encoded private key (in the clear).

Parameters:

prv the ASN.1 encoded private key to be loaded

Returns:

0 (success)CDK_KEY_INVALIDCDK_PARSE_ERRORCDK_INVALID_KEY_TOO_MANY_PRIMES (2, 3, or 4 prime keys only)

3.18.5.29 int loadpub (const str & pubk)

Load an ASN.1 encoded public key.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 138: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

132 Data Structure Documentation

Parameters:

pubk the ASN.1 encoded public key to be loaded

Returns:

0 (success)CDK_KEY_INVALIDnon-zero = failure

3.18.5.30 int loadseed (const str & seed, int np, int & counter)

Load DSA parameters based on a specified SEED.

Parameters:

seed the initial SEED value

np the length of the desired prime modulus in bits

counter an output buffer to receive the final counter value

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_SEEDCDK_INVALID_ALG_PARAMSCDK_INVALID_ITERATION_COUNT

3.18.5.31 num order () const [inline]

Get the order of this key’s underlying Abelian group.

Returns:

a num containing the order of the underlying Abelian group.

Remarks:

Use this function only with DL (DH/DSA/ECDH/ECDSA) keys.

3.18.5.32 bool permit (int flag) const [inline]

Predicate used to test keyUsage bit settings.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 139: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 133

Parameters:

flag the bit setting (enum value) to be tested against this object’s keyUsage

Returns:

true if flag is permittedfalse otherwise

3.18.5.33 int power (const num & a, num & x) const

Perform modular exponentiation with this object’s private key (for DH or ElGamal).

Parameters:

a the num to be raised to the private exponentx an output buffer for the result (a raised to the private exponent in the underlying

group)

Returns:

0 (success)CDK_ERROR_STATECDK_INTERNAL_ERR

3.18.5.34 int rawsiglength () const [inline]

Get the length in bytes of a raw signature associated with this key.

Returns:

the length in bytes of a raw signature generated with this key

3.18.5.35 int RSAGetRawPublic (num & expo1, num & pq1)

Get the raw RSA public key from this object.

Parameters:

expo1 an output buffer for the public exponentpq1 an output buffer for the public modulus

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_KEYTYPE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 140: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

134 Data Structure Documentation

3.18.5.36 int RSAkeygen (const str & seed, int nbits = 1024, const num &exponent = 65537, int factors = 2)

Generate an RSA keypair.

Parameters:

seed a random number to be used as a seed for the prime searches.

nbits the desired length of the modulus in bits

exponent the public exponent

factors the number of prime factors to use: 2, 3, or 4

Returns:

0 (success)CDK_ERROR_STATECDK_KEYPAIR_INCONSISTENT

3.18.5.37 int RSALoadPublic (const num & expo1, const num & pq1)

Load a raw RSA public key (exponent and modulus) into this object.

Parameters:

expo1 the exponent of the RSA public key to be loaded

pq1 the modulus of the RSA public key to be loaded

Returns:

0 (success)CDK_INVALID_KEYTYPECDK_ERROR_STATE

3.18.5.38 void setdefaulthash ()

Set the hashtype of this object to SHA-1.

Remarks:

Modifies: hashtype = hSHA1

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 141: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 135

3.18.5.39 int setorder (const num & q)

Set the order of this key’s underlying Abelian group.

Parameters:

q the order of the group

Returns:

0

Remarks:

Use this function only with DL (DH/DSA/ECDH/ECDSA) keys.

3.18.5.40 void SetPadding (int nPadding) [inline]

Set the RSA padding scheme to use when signing.

Parameters:

nPadding padding indicator: pkcs1 or x931

3.18.5.41 int setPrivate (const str & p) [inline]

Load a (raw) DSA or ECDSA private key into this object.

Parameters:

p the raw private key to be loaded

Returns:

0

3.18.5.42 void settype (const str & kyp)

Set this object’s key type and size.

Parameters:

kyp an ASCII description of the key type and size (e.g., "RSA-1024", "EC2-163",etc.)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 142: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

136 Data Structure Documentation

3.18.5.43 int Sign (const num & hash, const num & random, Signature & sig)const

Sign the specified message digest using this object’s private key.

Parameters:

hash the message digest to be signed

random a random number required for DL signatures (can be generated withnum(gens(20))

sig the Signature object that is to receive the result

Returns:

0 (success)CDK_ERROR_STATECDK_PRVKEY_CANNOT_FINDCDK_INVALID_KEYUSAGECDK_INTERNAL_ERRCDK_INVALID_SIGNATURE

3.18.5.44 int SignCheck (const num & hash, const str & sig) const

Check the validity of a specified signature against this object’s public key.

Parameters:

hash the message digest that was purportedly signed

sig a str containing the signature PDU (raw binary or ASN.1 DER-encoded) to beverified

Returns:

0 if public key could verify the signatureCDK_ERROR_STATECDK_INVALID_KEYUSAGECDK_INVALID_DIGESTCDK_INVALID_PADDINGCDK_INVALID_SIGNATURE

3.18.5.45 int SignCheck (const num & hash, const Signature & sig) const

Check the validity of a specified signature against this object’s public key.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 143: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.18 Key Struct Reference 137

Parameters:

hash the message digest that was purportedly signed

sig a Signature object containing the signature to be verified

Returns:

0, if signature is validCDK_ERROR_STATECDK_INVALID_KEYUSAGECDK_INVALID_DIGESTCDK_INVALID_PADDINGCDK_INVALID_SIGNATURE

3.18.5.46 T to () const

Convert this key object into an object of type T.

Returns:

a object of type T representating this key

The documentation for this struct was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 144: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

138 Data Structure Documentation

3.19 MD2 Class Reference

#include <md2.h>

Inheritance diagram for MD2:

MD2

Algorithm

Collaboration diagram for MD2:

MD2

Algorithm

3.19.1 Detailed Description

Implementation of the RFC 1319 MD2 message digest.

Usage flow:MD2() // construct new MD2 objectadd() // call as many times as necessary to process datafinal() // finalize message digest computationresult() // get 128-bit message digest value

Recommendations for strict FIPS 140-1 compliance:MD2 is not a FIPS approved algorithm, so the MD2 class should

*NOT* be used.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Message Digest Functions.

3.19.2 References

MD2 is specified in RFC1319.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 145: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.19 MD2 Class Reference 139

Public Member Functions

• MD2 (int v=0)

Constructor. Calls clear().

• ∼MD2 ()

Destructor. Calls clear().

• int add (int count, const char ∗buf)

Update message digest computation with contents of input buffer.

• int final (void)

Finalize the message digest computation.

• const char ∗ result () const

Get a pointer to the 16-byte message digest value.

• int length () const

Get the length of an MD2 value in bytes.

• int blocksize () const

Get the block size of the MD2 algorithm in bytes.

• template<class T> T to () const

Convert the message digest to type T.

• str tostr () const

Convert the message digest to a str:.

• void clear (void)

Clear MD2 object.

3.19.3 Constructor & Destructor Documentation

3.19.3.1 MD2 (int v = 0) [inline]

Constructor. Calls clear().

Parameters:

v unused; facilitates the use of templates elsewhere.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 146: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

140 Data Structure Documentation

Remarks:

Modifies: state, cksum, and data are zeroized.

3.19.3.2 ∼MD2 () [inline]

Destructor. Calls clear().

Remarks:

Modifies: state, cksum, and data are zeroized.

3.19.4 Member Function Documentation

3.19.4.1 int add (int count, const char ∗ buf)

Update message digest computation with contents of input buffer.

Parameters:

count length of input buffer in bytes

buf pointer to input buffer

Remarks:

Updates internal MD2 value.

Returns:

0 (success)CDK_INVALID_PTR

3.19.4.2 int blocksize () const [inline]

Get the block size of the MD2 algorithm in bytes.

Returns:

4 ∗ MD2_BLOCK (64)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 147: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.19 MD2 Class Reference 141

3.19.4.3 void clear (void)

Clear MD2 object.

Remarks:

Modifies: state, cksum, and data are zeroized.

3.19.4.4 int final (void)

Finalize the message digest computation.

Remarks:

Performs finalization step and sets internal state to FINAL.

Returns:

0 (success)CDK_ERROR_STATE

3.19.4.5 int length () const [inline]

Get the length of an MD2 value in bytes.

Returns:

MD2_LENGTH (16)

3.19.4.6 const char∗ result () const

Get a pointer to the 16-byte message digest value.

Returns:

a pointer to the final message digest NULL (if the CDK is in an error state)

3.19.4.7 T to () const [inline]

Convert the message digest to type T.

Returns:

a class T representation of the message digest value.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 148: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

142 Data Structure Documentation

3.19.4.8 str tostr () const

Convert the message digest to a str:.

Returns:

a string representation of the message digest value.

The documentation for this class was generated from the following file:

• md2.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 149: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.20 MD5 Class Reference 143

3.20 MD5 Class Reference

#include <md5.h>

Inheritance diagram for MD5:

MD5

Algorithm

Collaboration diagram for MD5:

MD5

Algorithm

3.20.1 Detailed Description

Implementation of the RFC 1321 MD5 message digest.

Usage flow:MD5() // construct new MD5 objectadd() // call as many times as necessary to process datafinal() // finalize message digest computationresult() // get 128-bit message digest value

Recommendations for strict FIPS 140-1 compliance:MD5 is not a FIPS approved algorithm, so the MD5 class should

*NOT* be used.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Message Digest Functions.

3.20.2 References

MD5 is specified in RFC1321.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 150: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

144 Data Structure Documentation

Public Member Functions

• MD5 (int v=0)

Constructor. Calls clear().

• ∼MD5 ()

Destructor. Calls clear().

• int add (int count, const char ∗buf)

Update the message digest computation with the contents of the input buffer.

• int final (void)

Finalize the message digest computation.

• const char ∗ result () const

Get a pointer to the 16-byte message digest value.

• int length () const

Get the length of an MD5 value in bytes.

• int blocksize () const

Get the block size of the MD5 algorithm in bytes.

• template<class T> T to () const

Convert the message digest to type T.

• str tostr () const

Convert the message digest to a str:.

• void clear (void)

Clear MD5 object.

3.20.3 Constructor & Destructor Documentation

3.20.3.1 MD5 (int v = 0) [inline]

Constructor. Calls clear().

Parameters:

v unused; facilitates the use of templates elsewhere.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 151: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.20 MD5 Class Reference 145

Remarks:

Modifies: state, cksum, and data are zeroized.

3.20.3.2 ∼MD5 () [inline]

Destructor. Calls clear().

Remarks:

Modifies: state, cksum, and data are zeroized.

3.20.4 Member Function Documentation

3.20.4.1 int add (int count, const char ∗ buf)

Update the message digest computation with the contents of the input buffer.

Parameters:

count length of input buffer in bytes

buf pointer to input buffer

Remarks:

Updates internal MD5 value.

Returns:

0 (success)CDK_INVALID_PTR

3.20.4.2 int blocksize () const [inline]

Get the block size of the MD5 algorithm in bytes.

Returns:

4 ∗ MD5_BLOCK (64)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 152: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

146 Data Structure Documentation

3.20.4.3 void clear (void)

Clear MD5 object.

Remarks:

Modifies: The object is reset to the initial state (MD5_Init is called).

3.20.4.4 int final (void)

Finalize the message digest computation.

Remarks:

Performs finalization step and sets internal state to FINAL.

Returns:

0 (success)CDK_ERROR_STATE

3.20.4.5 int length () const [inline]

Get the length of an MD5 value in bytes.

Returns:

MD5_LENGTH (16)

3.20.4.6 const char∗ result () const

Get a pointer to the 16-byte message digest value.

Returns:

a pointer to the final message digest NULL (if the CDK is in an error state)

3.20.4.7 T to () const [inline]

Convert the message digest to type T.

Returns:

a class T representation of the message digest value.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 153: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.20 MD5 Class Reference 147

3.20.4.8 str tostr () const

Convert the message digest to a str:.

Returns:

a string representation of the message digest value.

The documentation for this class was generated from the following file:

• md5.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 154: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

148 Data Structure Documentation

3.21 Nat Class Reference

#include <pk.h>

3.21.1 Detailed Description

Data type used to represent elements of various algebraic objects.

Public Types

• typedef Nat const & cNat

const reference to a Nat

Public Member Functions

Inspectors

• int bit (int k) constGet k-th bit of this object.

• int degree () constGet length of this object in bits.

• int length () constGet length of this object in nwords.

Arithmetic and Logical Operations

• void add1 (cnat y)Add number to this one.

• void sub1 (cnat y)Subtract number from this one.

• void subr (cnwordp a)Subtract this object from another.

• void extend (int n)Extend length of this object by specified number of nwords.

• void shiftright (int k=1)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 155: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.21 Nat Class Reference 149

Right shift this object by a specified number of bits.

• void shiftleft (int k=1)Left shift this object by a specified number of bits.

• void xorshift (int k, cnat a)Left shift number and XOR into this object.

Assignment and Arithmetic Operators

• Nat & operator= (nword x)Assignment operator.

• Nat & operator= (const Nat &x)Assignment operator.

• void operator+= (cnat y)Increment this object by a specified amount.

• void operator-= (cnat y)Decrement this object by a specified amount.

Predicates

• bool isOdd () constPredicate to test oddness.

• bool isEven () constPredicate to test evenness.

• bool operator== (nword n) constPredicate to test equality of natural numbers.

• bool operator!= (nword n) constPredicate to test inequality of natural numbers.

• bool operator== (cNat x) constPredicate to test equality of Nat objects.

• bool operator!= (cNat x) constPredicate to test inequality of Nat objects.

• bool operator<= (cNat x) constPredicate to test "less than or equal to" relation between Nat objects.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 156: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

150 Data Structure Documentation

• bool operator>= (cNat x) constPredicate to test "greater than or equal to" relation between Nat objects.

• bool operator< (cNat x) constPredicate to test "less than" relation between Nat objects.

• bool operator> (cNat x) constPredicate to test "greater than" relation between Nat objects.

3.21.2 Member Function Documentation

3.21.2.1 void add1 (cnat y)

Add number to this one.

Parameters:

y object to add to this object

3.21.2.2 int bit (int k) const

Get k-th bit of this object.

Parameters:

k index of bit to return

Returns:

k-th bit of the natural number represented by this object

3.21.2.3 int degree () const

Get length of this object in bits.

Returns:

log2(x)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 157: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.21 Nat Class Reference 151

3.21.2.4 void extend (int n)

Extend length of this object by specified number of nwords.

Parameters:

n new size of object in nwords.

Remarks:

Modifies: w is padded with zeros so len >= n

3.21.2.5 bool isEven () const [inline]

Predicate to test evenness.

Returns:

true, if the number stored in this object is evenfalse otherwise

3.21.2.6 bool isOdd () const [inline]

Predicate to test oddness.

Returns:

true, if the number stored in this object is oddfalse, otherwise.

3.21.2.7 int length () const [inline]

Get length of this object in nwords.

Returns:

len (i.e., number of nwords are used by this object)

3.21.2.8 bool operator!= (cNat x) const [inline]

Predicate to test inequality of Nat objects.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 158: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

152 Data Structure Documentation

Parameters:

x Nat object to which this one is to be compared

Returns:

true, if x != thisfalse, if x == this

3.21.2.9 bool operator!= (nword n) const [inline]

Predicate to test inequality of natural numbers.

Parameters:

n nword to compare with this object.

Returns:

true, if this object does not equal nfalse, if they are equal

3.21.2.10 void operator+= (cnat y)

Increment this object by a specified amount.

Parameters:

y the number to add to this object

3.21.2.11 void operator-= (cnat y) [inline]

Decrement this object by a specified amount.

Parameters:

y number to be sutracted from this object

3.21.2.12 bool operator< (cNat x) const [inline]

Predicate to test "less than" relation between Nat objects.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 159: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.21 Nat Class Reference 153

Parameters:

x Nat object to which this one is to be compared

Returns:

true, if x < thisfalse, otherwise

3.21.2.13 bool operator<= (cNat x) const [inline]

Predicate to test "less than or equal to" relation between Nat objects.

Parameters:

x Nat object to which this one is to be compared

Returns:

true, if x <= thisfalse, otherwise

3.21.2.14 Nat& operator= (const Nat & x)

Assignment operator.

Parameters:

x Nat to assign to this object

Returns:

a reference to this object

Remarks:

Modifies: w (x.w is copied into this.w).Warning: this.len ∗must∗ be >= x.len

3.21.2.15 Nat& operator= (nword x)

Assignment operator.

Parameters:

x nword to assign to this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 160: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

154 Data Structure Documentation

Returns:

a reference to this object

Remarks:

Modifies: w (this object becomes a Nat with len = 1)

3.21.2.16 bool operator== (cNat x) const [inline]

Predicate to test equality of Nat objects.

Parameters:

x Nat object to which this one is to be compared

Returns:

true, if x == thisfalse, if x != this

3.21.2.17 bool operator== (nword n) const

Predicate to test equality of natural numbers.

Parameters:

n nword to compare with this object.

Returns:

true, if this object equals nfalse, if they are unequal

3.21.2.18 bool operator> (cNat x) const [inline]

Predicate to test "greater than" relation between Nat objects.

Parameters:

x Nat object to which this one is to be compared

Returns:

true, if x > thisfalse, otherwise

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 161: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.21 Nat Class Reference 155

3.21.2.19 bool operator>= (cNat x) const [inline]

Predicate to test "greater than or equal to" relation between Nat objects.

Parameters:

x Nat object to which this one is to be compared

Returns:

true, if x >= thisfalse otherwise

3.21.2.20 void shiftleft (int k = 1)

Left shift this object by a specified number of bits.

Parameters:

k number of bits to left shift this object.

3.21.2.21 void shiftright (int k = 1)

Right shift this object by a specified number of bits.

Parameters:

k number of bits to right shift this object.

3.21.2.22 void sub1 (cnat y)

Subtract number from this one.

Parameters:

y object to subtract from this object

3.21.2.23 void subr (cnwordp a)

Subtract this object from another.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 162: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

156 Data Structure Documentation

Parameters:

a object from which to subtract this object

Remarks:

Modifies: w = a - this.w

3.21.2.24 void xorshift (int k, cnat a)

Left shift number and XOR into this object.

Parameters:

k number of bits to leftshift a

a number to XOR with this Modifies: w (this gets the result of this XOR’d with aleft shifted k bits).

The documentation for this class was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 163: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 157

3.22 num Struct Reference

#include <pk.h>

Collaboration diagram for num:

num

FParms

p

Parameters Nat

v

primeinvbc

3.22.1 Detailed Description

Implementation of the arithmetic in various groups, rings, and fields.

Public Member Functions

Constructors and Destructors

• num ()Constructor.

• num (const num &x)Constructor used to duplicate a given num object.

• num (const num &x, const str &y)Constructor used to convert a str into a num object with specified parameters.

• num (int x)Constructor used to instantiate a new num object based on an integer.

• num (const FParms ∗p1)Constructor used to create new num with specified parameters.

• num (const str &x)Constructor used to convert a str into a num object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 164: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

158 Data Structure Documentation

• num (int type1, int len)Constructor used to created a new num object of specified type and size.

• ∼num ()Destructor. Calls clear1().

Initializers

• void setlen (int n)Set the length of this object in nwords.

• void add (int n, const char ∗x)Load octet string into this object.

• void mod2to (int n)Assign a power of 2 to this object.

Assignment and Arithmetic Operators

• void operator= (const FParms ∗p1)Assign parameters to this object.

• void operator= (const num &x)Assignment operator for num objects.

• num operator & (const FParms ∗p1) constChange this object’s parameters, but not its value.

• num & operator= (nword x)Assignment operator for nword.

• num & operator= (int x)Assignment operator for int.

• num & operator-= (int x)Decrement this object by a specified integer.

• num operator- () constNegate this object.

• num operator- (int x)Subtract an integer from this object.

• num operator+ (const num &y) constAdd a num object to this one.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 165: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 159

• num operator- (const num &y) constSubtract a num object from this one.

• num operator ∗ (int y) constMultiply this object by an integer.

• num operator ∗ (const num &y) constMultiply this num by another one.

• num operator/ (int y) constDivide this num by an integer.

• num operator/ (const num &x) constDivide this num by another num.

• num & operator+= (const num &x)Increment this object by a specified value.

• num & operator-= (const num &x)Decrement this object by a specified value.

• int operator% (int k) constCompute this num’s residue modulo a specified integer.

• num operator∧ (int n) constRaise this object’s value to an integer exponent.

• num & operator ∗= (int n)Multiply this num by an integer.

• num & operator/= (int n)Divide this object by an integer.

Arithmetic Predicates

• bool isNeg () constPredicate used to determine if this object is negative.

• bool isNat () constPredicate used to determine if this object represents a natural number.

• bool isMod () constPredicate used to determine if this object is a ring or field element.

• bool isChar2 () const

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 166: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

160 Data Structure Documentation

Predicate used to determine if this object is an element of a field of char 2.

• bool isEven () constPredicate used to determine if this object is even.

• bool isZero () constPredicate used to determine if this object is the zero element.

• bool isPrime (int rounds=8) constPredicate used to test primality.

• bool isIrred () constPredicate used to test irreducibility.

• bool isMontg () constPredicate used to determine if this object is in its Montgomery representation.

• int isSquare () constPredicate to test quadratic residuosity.

Operator Predicates

• bool operator| (const num &y) constPredicate used to test whether a given num divides this one.

• bool operator== (const num &y) constPredicate to test equality of two nums.

• bool operator!= (const num &y) constPredicate to test inequality of two nums.

• bool operator== (int n) constPredicate to test equality of this oject with an int.

• bool operator!= (int n) constPredicate to test inequality of this oject with an int.

• bool operator< (const num &y) constPredicate to test "less than" relation between two nums.

• bool operator<= (const num &y) constPredicate to test "less than or equal to" relation between two nums.

• bool operator> (const num &y) constPredicate to test "greater than" relation between two nums.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 167: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 161

• bool operator>= (const num &y) constPredicate to test "greater than or equal to" relation between two nums.

• bool operator> (int n) constPredicate to test "greater than" relation with an int.

• bool operator< (int n) constPredicate to test "less than" relation with an int.

• bool operator<= (int n) constPredicate to test "less than or equal to" relation with an int.

• bool operator>= (int n) constPredicate to test "greater than or equal to" relation with an int.

Arithmetic Functions

• num abs () constAbsolute value of this object.

• num sqrt () constCalculate square root.

• void mmult (const num &x, const num &y)Assign the product of two num objects to this one.

• void divide (const num &y, num &quot, num &rem) constDivide this num by another.

• num mod1 (const num &y, int deg=0) constModular reduction.

• num mod (const num &y, int deg=0) constModular reduction. Alias for mod1().

• num mod2 (const num &y) constModular reduction.

• num inverse () constCompute the inverse of this object (uses Euclidean Algorithm).

• void power (const num &x, const num &y)Assign x∧y to this object.

• num reciprocal () constInvert this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 168: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

162 Data Structure Documentation

• void square ()Square this object.

• void square (int k)Square this object a specified number of times.

• void square (const num &x)Assign the square of another num to this object.

• void mpower (const num &x, const num &y)Exponentiation: assign x∧y to this object.

Inspectors

• int bytes () constGet the length of this object’s value in bytes.

• int l () constGet the length of this object in nwords.

• int bits () constGet the number of bits in this object’s representation.

• int bit (int k) constGet the kth bit of this object’s value.

• int byte (int k) const

Get the kth element in the array of bytes representing this object’s value.

• nword & wd (int k)Get reference to kth nword in the representation of this object as an array ofnwords.

• nword w (int k) constGet kth nword in the representation of this object as an array of nwords.

• const nword ∗ words () constGet a pointer to the array of nwords representing this object.

• int degree () constGet object’s degree.

• int degf () constGet the degree of the underlying field extension in characteristic 2.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 169: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 163

• num modulus () constGet the characteristic of the underlying field.

• num modulus2 () constGet the degree of the field extension in char 2.

• const FParms ∗ parms () constGet the parameters of the underlying group, ring, or field.

• int checkModulus () constTest object’s parameters.

Conversions

• num toint () constMap this object to a natural number.

• template<class T> T to (int n=0) constConvert this object to type T.

• cdk::str tostr (int n=0) constGet a str representation of this object.

3.22.2 Constructor & Destructor Documentation

3.22.2.1 num (const num & x) [inline]

Constructor used to duplicate a given num object.

Parameters:

x num to duplicate in this object

3.22.2.2 num (const num & x, const str & y) [inline]

Constructor used to convert a str into a num object with specified parameters.

Parameters:

x num whose parameters are to be copied

y str to convert into this num object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 170: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

164 Data Structure Documentation

3.22.2.3 num (int x) [inline]

Constructor used to instantiate a new num object based on an integer.

Parameters:

x int to be assigned to this new num object.

3.22.2.4 num (const FParms ∗ p1) [inline]

Constructor used to create new num with specified parameters.

Parameters:

p1 parameters to use for this new num object.

3.22.2.5 num (const str & x) [explicit]

Constructor used to convert a str into a num object.

Parameters:

x str to be converted into this num.

3.22.2.6 num (int type1, int len) [inline]

Constructor used to created a new num object of specified type and size.

Parameters:

type1 one of FParms::Types

len size of num object to be created

3.22.2.7 ∼num () [inline]

Destructor. Calls clear1().

Remarks:

Modifies: v (zeroized as v may have held a key), p

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 171: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 165

3.22.3 Member Function Documentation

3.22.3.1 num abs () const

Absolute value of this object.

Returns:

a positive representation of this num with the same absolute value

3.22.3.2 void add (int n, const char ∗ x) [inline]

Load octet string into this object.

Parameters:

n length of input array in nwords

x pointer to an octet string (base 256) to assign to this object.

3.22.3.3 int bit (int k) const [inline]

Get the kth bit of this object’s value.

Parameters:

k the index of the bit to be returned

Returns:

the kth bit of this object’s value

3.22.3.4 int bits () const [inline]

Get the number of bits in this object’s representation.

Returns:

1 plus the object’s degree

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 172: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

166 Data Structure Documentation

3.22.3.5 int byte (int k) const [inline]

Get the kth element in the array of bytes representing this object’s value.

Parameters:

k index of byte to return

Returns:

the kth byte of the num

3.22.3.6 int bytes () const [inline]

Get the length of this object’s value in bytes.

Returns:

the size of the num in bytes

3.22.3.7 int checkModulus () const

Test object’s parameters.

Returns:

0, if the object’s parameters are prime/irreduciblenon-zero, otherwise

3.22.3.8 int degf () const [inline]

Get the degree of the underlying field extension in characteristic 2.

Returns:

the degree of the field extension containing this object

3.22.3.9 int degree () const [inline]

Get object’s degree.

Returns:

the degree of this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 173: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 167

3.22.3.10 void divide (const num & y, num & quot, num & rem) const

Divide this num by another.

Parameters:

y num by which to divide this objectquot buffer which is to receive quotientrem buffer which is to receive remainder

3.22.3.11 num inverse () const

Compute the inverse of this object (uses Euclidean Algorithm).

Returns:

a num containing the inverse of this object

3.22.3.12 bool isChar2 () const [inline]

Predicate used to determine if this object is an element of a field of char 2.

Returns:

true, if type is Char2false, otherwise

3.22.3.13 bool isEven () const [inline]

Predicate used to determine if this object is even.

Returns:

true, if object is evenfalse, otherwise

3.22.3.14 bool isIrred () const

Predicate used to test irreducibility.

Returns:

true, if this object is irreduciblefalse, otherwise

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 174: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

168 Data Structure Documentation

3.22.3.15 bool isMod () const [inline]

Predicate used to determine if this object is a ring or field element.

Returns:

true, if type is Modularfalse, otherwise

3.22.3.16 bool isMontg () const [inline]

Predicate used to determine if this object is in its Montgomery representation.

Returns:

true, if this object is in its Montgomery representationfalse, otherwise

3.22.3.17 bool isNat () const [inline]

Predicate used to determine if this object represents a natural number.

Returns:

true, if type is Naturalfalse, otherwise

3.22.3.18 bool isNeg () const [inline]

Predicate used to determine if this object is negative.

Returns:

true, if type is Negativefalse, otherwise

3.22.3.19 bool isPrime (int rounds = 8) const

Predicate used to test primality.

Parameters:

rounds number of Miller-Rabin rounds to run

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 175: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 169

Returns:

true, if this object passes the test (i.e., is a probable prime)false, if this object is composite

3.22.3.20 int isSquare () const

Predicate to test quadratic residuosity.

Returns:

+1 if this is a square mod p

3.22.3.21 bool isZero () const [inline]

Predicate used to determine if this object is the zero element.

Returns:

true, if object is the additive identityfalse otherwise

3.22.3.22 int l () const [inline]

Get the length of this object in nwords.

Returns:

the length of this object in nwords

3.22.3.23 void mmult (const num & x, const num & y)

Assign the product of two num objects to this one.

Parameters:

x multiplicand

y multiplier

Remarks:

This object receives the value x ∗ y.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 176: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

170 Data Structure Documentation

3.22.3.24 num mod (const num & y, int deg = 0) const [inline]

Modular reduction. Alias for mod1().

Parameters:

y modulusdeg 0 for char p; degree of the field extension in char 2

Returns:

this object reduced modulo y

3.22.3.25 num mod1 (const num & y, int deg = 0) const

Modular reduction.

Parameters:

y modulusdeg 0 for char p; degree of the field extension in char 2

Returns:

this reduced mod y

3.22.3.26 num mod2 (const num & y) const [inline]

Modular reduction.

Parameters:

y modulus

Returns:

this object reduced modulo y

3.22.3.27 void mod2to (int n)

Assign a power of 2 to this object.

Parameters:

n exponent to which 2 is to be raised before storing in this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 177: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 171

3.22.3.28 num modulus () const

Get the characteristic of the underlying field.

Returns:

the characteristic of the underlying field (a large prime)

3.22.3.29 num modulus2 () const

Get the degree of the field extension in char 2.

Returns:

the degree of the field extension in char 2

3.22.3.30 void mpower (const num & x, const num & y)

Exponentiation: assign x∧y to this object.

Parameters:

x basey exponent

3.22.3.31 num operator & (const FParms ∗ p1) const

Change this object’s parameters, but not its value.

Parameters:

p1 pointer to new parameters to use this num object.

3.22.3.32 num operator ∗ (const num & y) const

Multiply this num by another one.

Parameters:

y num by which to multiply this num

Returns:

a num representing this object’s value ∗ y’s value

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 178: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

172 Data Structure Documentation

3.22.3.33 num operator ∗ (int y) const

Multiply this object by an integer.

Parameters:

y int by which this object is to be multiplied

Returns:

a num representing this object’s value times y

3.22.3.34 num& operator ∗= (int n)

Multiply this num by an integer.

Parameters:

n integer multiplier

Returns:

a reference to this object

3.22.3.35 bool operator!= (int n) const [inline]

Predicate to test inequality of this oject with an int.

Parameters:

n int to which this object is to be compared

Returns:

true, if this object is not equal to nfalse, otherwise

3.22.3.36 bool operator!= (const num & y) const [inline]

Predicate to test inequality of two nums.

Parameters:

y num to which this object is to be compared

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 179: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 173

Returns:

true, if this object is not equal to yfalse, otherwise

3.22.3.37 int operator% (int k) const

Compute this num’s residue modulo a specified integer.

Parameters:

k modulus

Returns:

remainder obtained by dividing this object by k

3.22.3.38 num operator+ (const num & y) const

Add a num object to this one.

Parameters:

y the num to added to this object.

Returns:

a num representing this object’s value plus y’s value

3.22.3.39 num& operator+= (const num & x)

Increment this object by a specified value.

Parameters:

x num to add to this one

Returns:

a reference to this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 180: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

174 Data Structure Documentation

3.22.3.40 num operator- (const num & y) const

Subtract a num object from this one.

Parameters:

y the num to subtracted from this object.

Returns:

a num representing this object’s value minus y’s value

3.22.3.41 num operator- (int x) [inline]

Subtract an integer from this object.

Parameters:

x int to be subtracted from this object.

Returns:

a num representing this object’s value minus x

3.22.3.42 num operator- () const

Negate this object.

Returns:

a negated copy of this object

Remarks:

If this object represents A, then a num representing -A is returned.

3.22.3.43 num& operator-= (const num & x)

Decrement this object by a specified value.

Parameters:

x num to subtract from this one

Returns:

a reference to this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 181: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 175

3.22.3.44 num& operator-= (int x) [inline]

Decrement this object by a specified integer.

Parameters:

x int to be subtracted from this object.

Returns:

a reference to this object

3.22.3.45 num operator/ (const num & x) const [inline]

Divide this num by another num.

Parameters:

x divisor

Returns:

a num representing this object’s value divided by x’s value

3.22.3.46 num operator/ (int y) const

Divide this num by an integer.

Parameters:

y the integer divisor

Returns:

a num representing this object’s value divided by y

3.22.3.47 num& operator/= (int n)

Divide this object by an integer.

Parameters:

n int divisor

Returns:

a reference to this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 182: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

176 Data Structure Documentation

3.22.3.48 bool operator< (int n) const [inline]

Predicate to test "less than" relation with an int.

Parameters:

n int to which this object is to be compared

Returns:

true, if this object is less than nfalse, otherwise

3.22.3.49 bool operator< (const num & y) const

Predicate to test "less than" relation between two nums.

Parameters:

y num to which this object is to be compared

Returns:

true, if this object is less than yfalse, otherwise

3.22.3.50 bool operator<= (int n) const [inline]

Predicate to test "less than or equal to" relation with an int.

Parameters:

n int to which this object is to be compared

Returns:

true, if this object is less than or equal to nfalse, otherwise

3.22.3.51 bool operator<= (const num & y) const

Predicate to test "less than or equal to" relation between two nums.

Parameters:

y num to which this object is to be compared

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 183: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 177

Returns:

true, if this object is less than or equal to yfalse, otherwise

3.22.3.52 num& operator= (int x)

Assignment operator for int.

Parameters:

x int to be assigned to this object.

Returns:

a reference to this object

3.22.3.53 num& operator= (nword x)

Assignment operator for nword.

Parameters:

x nword to to be assigned to this object.

Returns:

a reference to this object

3.22.3.54 void operator= (const num & x) [inline]

Assignment operator for num objects.

Parameters:

x num to copy into this num object.

3.22.3.55 void operator= (const FParms ∗ p1) [inline]

Assign parameters to this object.

Parameters:

p1 new parameters to use for this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 184: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

178 Data Structure Documentation

3.22.3.56 bool operator== (int n) const

Predicate to test equality of this oject with an int.

Parameters:

n int to which this object is to be compared

Returns:

true, if this object is equal to nfalse, otherwise

3.22.3.57 bool operator== (const num & y) const

Predicate to test equality of two nums.

Parameters:

y num to which this object is to be compared

Returns:

true, if this object is equal to yfalse, otherwise

3.22.3.58 bool operator> (int n) const [inline]

Predicate to test "greater than" relation with an int.

Parameters:

n int to which this object is to be compared

Returns:

true, if this object is greater than nfalse, otherwise

3.22.3.59 bool operator> (const num & y) const [inline]

Predicate to test "greater than" relation between two nums.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 185: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 179

Parameters:

y num to which this object is to be compared

Returns:

true, if this object is greater than yfalse, otherwise

3.22.3.60 bool operator>= (int n) const

Predicate to test "greater than or equal to" relation with an int.

Parameters:

n int to which this object is to be compared

Returns:

true, if this object is greater than or equal to nfalse, otherwise

3.22.3.61 bool operator>= (const num & y) const [inline]

Predicate to test "greater than or equal to" relation between two nums.

Parameters:

y num to which this object is to be compared

Returns:

true, if this object is greater than or equal to yfalse, otherwise

3.22.3.62 num operator∧ (int n) const

Raise this object’s value to an integer exponent.

Parameters:

n exponent

Returns:

a num = this ∧ n if n < 1000 (if n >= 1000 an assertion occurs)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 186: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

180 Data Structure Documentation

3.22.3.63 bool operator| (const num & y) const [inline]

Predicate used to test whether a given num divides this one.

Parameters:

y divisor

Returns:

true, if y divides this objectfalse, otherwise

3.22.3.64 const FParms∗ parms () const [inline]

Get the parameters of the underlying group, ring, or field.

Returns:

a pointer to this object’s parameters

3.22.3.65 void power (const num & x, const num & y)

Assign x∧y to this object.

Parameters:

x the base

y the exponent

3.22.3.66 num reciprocal () const

Invert this object.

Returns:

a num containing the reciprocal of this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 187: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 181

3.22.3.67 void setlen (int n) [inline]

Set the length of this object in nwords.

Parameters:

n the number of nwords to use for this num.

Remarks:

WARNING: This call is dangerous!

3.22.3.68 num sqrt () const

Calculate square root.

Returns:

the square root of this object

3.22.3.69 void square (const num & x) [inline]

Assign the square of another num to this object.

Parameters:

x the num to be squared

3.22.3.70 void square (int k)

Square this object a specified number of times.

Parameters:

k number of times to square this object

3.22.3.71 T to (int n = 0) const

Convert this object to type T.

Parameters:

n minimum size of output in bytes

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 188: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

182 Data Structure Documentation

Returns:

a type T represenation of this object (typically a str representation with leading 0’sremoved)

3.22.3.72 num toint () const

Map this object to a natural number.

Returns:

a num containing this object’s value but without parameter information

3.22.3.73 cdk::str tostr (int n = 0) const

Get a str representation of this object.

Parameters:

n the minimum length of the str to be created

Returns:

a (binary) str representation of the value of this num

3.22.3.74 nword w (int k) const [inline]

Get kth nword in the representation of this object as an array of nwords.

Parameters:

k index of nword to return

Returns:

the kth nword

3.22.3.75 nword& wd (int k) [inline]

Get reference to kth nword in the representation of this object as an array of nwords.

Parameters:

k index of nword to return

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 189: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.22 num Struct Reference 183

Returns:

a reference to the kth nword

3.22.3.76 const nword∗ words () const [inline]

Get a pointer to the array of nwords representing this object.

Returns:

a reference to the array of nwords stored in this Nat object

The documentation for this struct was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 190: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

184 Data Structure Documentation

3.23 Parameters Struct Reference

#include <pk.h>

Inheritance diagram for Parameters:

Parameters

FParms GParms

3.23.1 Detailed Description

Base class for arithmetic parameters (used to define various algebraic structures).

Public Member Functions

• Parameters ()Constructor.

The documentation for this struct was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 191: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.24 party Struct Reference 185

3.24 party Struct Reference

#include <tls.h>

Collaboration diagram for party:

party

RC4

rc4i

Algorithm

DES AES str

temprandcryptmaccerivbuf

desi aesi

3.24.1 Detailed Description

Internal data type used by the implementation of class TLS to encapsulate variouscryptographic operations.

Public Member Functions

Constructor

• party (int sflag)Constructor.

Object Reuse and Initialization

• void clear ()Clear this object’s communications buffer and certificate cache.

• void init (const str &key, const str &iv)Load an RC4, DES, TDES, or AES key and IV.

Predicates

• bool isClient () constPredicate used to determine if this object represents a client or a server.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 192: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

186 Data Structure Documentation

Data Fields

• str bufcommunications buffer

• str certhis party’s certificate cache

3.24.2 Constructor & Destructor Documentation

3.24.2.1 party (int sflag) [inline]

Constructor.

Parameters:

sflag client/server indicator: 0 for client, 1 for server

3.24.3 Member Function Documentation

3.24.3.1 void init (const str & key, const str & iv)

Load an RC4, DES, TDES, or AES key and IV.

Parameters:

key an RC4, DES or AES key

iv an IV for DES-CBC, TDES-CBC, or AES-CBC mode

Remarks:

If +iv=8, key must be an 8-byte DES-CBC key, or a 16- or 24-byte TDES key;if +iv=16, key is assumed to be an AES key and must be 16, 24, or 32 bytes inlength.

The documentation for this struct was generated from the following file:

• tls.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 193: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.25 Password Class Reference 187

3.25 Password Class Reference

#include <pass.h>

Inheritance diagram for Password:

Password

Algorithm

Collaboration diagram for Password:

Password

Algorithm

3.25.1 Detailed Description

Implementation of the NIST FIPS 181 Automated Password Generator.

Usage flow:Password() // instantiate a Password objectinit() // seed its internal pseudorandom number generatorSuggestPassword() // call as often as desired to obtain pronouceable passwords

Recommendations for strict FIPS 140-1 compliance:This class produces pronouncable passwords according to FIPS 181. It providesand uses only FIPS approved functions.

3.25.2 References

The NIST Automated Password Generator is specified in FIPS 181.

Public Member Functions

• _cdkpub int init (const char ∗r24, const char ∗oldpass, int test1=0)

Initialize this Password object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 194: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

188 Data Structure Documentation

• _cdkpub int SuggestPassword (int min, int max, char ∗without, char ∗with)Get a pronounceable password in the specified length range.

3.25.3 Member Function Documentation

3.25.3.1 _cdkpub int init (const char ∗ r24, const char ∗ oldpass, int test1 = 0)

Initialize this Password object.

Parameters:

r24 a pointer to 24 random bytes (possibly generated by PRNG::gens(24))oldpass a pointer to (no more than 8) random bytestest1 FIPS 140-1 compliance flag: 0 prevents the internal daytime function from

collecting real time information. Used only for test purposes; see cdk::Test_-PWD_Generator().

Returns:

0

3.25.3.2 _cdkpub int SuggestPassword (int min, int max, char ∗ without, char ∗with)

Get a pronounceable password in the specified length range.

Parameters:

min a minimum length for the requested password (must be positive)max a maximum length for the requested password (must be greater than or equal

to min)without a pointer to an output buffer (of size max+1) for the generated passwordwith a pointer to an output buffer (of size 2∗max) for the password with hyphens

inserted (as an aid to pronunciation)

Returns:

0 (success)1 or CDK_ERROR_STATE (failure)

The documentation for this class was generated from the following file:

• pass.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 195: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.26 Point Class Reference 189

3.26 Point Class Reference

#include <pk.h>

Collaboration diagram for Point:

Point

GParms

p

Parameters

FParms

num

xyz

T 2T 3T4T5abT1

p

Nat

v

primeinvbc

3.26.1 Detailed Description

Data type used to represent the elements of, and abstract the operations in, variousAbelian groups, including elliptic curves.

As the class name indicates, operators are defined as if the underlying group operationis written additively, though obviously if the group is more commonly written multi-plicatively, the operators should be interpreted that way. For example, operator∗() isdecribed below as scalar multiplication, but should be thought of as exponentiation inthe multiplicative setting.

Public Member Functions

Constructors and Destructors

• Point ()

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 196: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

190 Data Structure Documentation

Constructor used to create an empty Point object.

• Point (const Point &a)Copy constructor.

• Point (const GParms ∗p1)Constructor used to create an element of the specified Abelian group.

• Point (const Point &a, const str &b)Constructor used to create a Point in the same Abelian group as another Point.

• virtual ∼Point ()Destructor.

Object Reuse and Initialization

• void clear ()Clear this Point object.

• int setgen (const num &g)Specify a generator for the underlying Abelian group.

• int setcurve (const num &a, const num &b)Specify the coefficients in the equation of an elliptic curve:

in char p: y 2 = x 3 + a x + bin char 2: y 2 + x y = x 3 + a x 2 + b.

• void power (const Point &x, const num &y)Assign an (unnormalized) multiple of a given Point to this one.

• int loadbin (int n, const char ∗b)Load an octet string into this Point.

• void add (int n, const char ∗b)Add; a void version of loadbin().

Assignment and Arithmetic Operators

• void operator= (int n)Assignment operator used to make this Point the identity element in the group.

• void operator= (const Point &x)Assignment operator used to copy Points.

• Point operator- () const

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 197: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.26 Point Class Reference 191

Get the additive inverse of this Point.

• Point operator+ (const Point &y) constAdd another Point to this one.

• Point operator- (const Point &y) constSubtract another Point from this one.

• Point operator ∗ (const num &x) constMultiply this Point by an integer.

Predicate Operators

• bool operator== (int n) constPredicate used to test whether this Point is the identity element in the group.

• bool operator!= (int n) constPredicate used to test whether this Point differs from the identity element.

• bool operator== (const Point &x) constPredicate used to test the equality of this Point with another one.

• bool operator!= (const Point &x) constPredicate used to test the inequality of this Point with another one.

Predicate Functions

• bool isDef () constPredicate used to determine whether parameters are defined.

• bool isDH () constPredicate used to determine whether this point is an element of (a multiplicativesubgroup of) the group of nonzero integers modulo a large prime.

• bool isEC () constPredicate used to determine whether this Point is on an elliptic curve.

• bool isChar2 () constPredicate used to determine whether this Point is on an elliptic curve in char 2.

• bool isValid () constPredicate used to test whether this Point lies on the underlying elliptic curve.

• bool hasOrder (const num &a) constPredicate used to test whether this group element has a specified order.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 198: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

192 Data Structure Documentation

Inspectors

• int bits () constGet the number of bits required to represent this Point.

• int length () constGet the size in bytes of the largest integer that can be mapped into the currentAbelian group.

• num modulus2 () constGet the order of the underlying finite field or order of the group.

Conversions

• cdk::str tostr (int n=0) constConvert this Point into a str.

• template<class T> T to (int opt=0) constConvert Point into an object of type T.

3.26.2 Constructor & Destructor Documentation

3.26.2.1 Point (const Point & a) [inline]

Copy constructor.

Parameters:

a the Point to copy into this Point

3.26.2.2 Point (const GParms ∗ p1) [inline, explicit]

Constructor used to create an element of the specified Abelian group.

Parameters:

p1 a pointer to the group parameters (GParms) to use for this point.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 199: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.26 Point Class Reference 193

3.26.2.3 Point (const Point & a, const str & b) [explicit]

Constructor used to create a Point in the same Abelian group as another Point.

Parameters:

a a Point from which to copy group parametersb a value indicating which group element this new Point is to represent

3.26.2.4 virtual ∼Point () [inline, virtual]

Destructor.

Remarks:

Modifies: p (x, y, and z are zeroized by their destructors)

3.26.3 Member Function Documentation

3.26.3.1 void add (int n, const char ∗ b) [inline]

Add; a void version of loadbin().

Parameters:

n length of the octet string in bytesb pointer to the octet string

3.26.3.2 int bits () const

Get the number of bits required to represent this Point.

Returns:

the number of bits in the point

3.26.3.3 void clear (void) [inline]

Clear this Point object.

Remarks:

Modifies: x, y, z are zeroized; p (the parameters) is not cleared.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 200: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

194 Data Structure Documentation

3.26.3.4 bool hasOrder (const num & a) const

Predicate used to test whether this group element has a specified order.

Parameters:

a suspected order of this group element

Returns:

true, if this element has order afalse, otherwise

3.26.3.5 bool isChar2 () const [inline]

Predicate used to determine whether this Point is on an elliptic curve in char 2.

Returns:

true, if this Point’s parameters are those for an elliptic curve over a finite field ofchar 2false, otherwise

3.26.3.6 bool isDef () const [inline]

Predicate used to determine whether parameters are defined.

Returns:

true, if the parameters are definedfalse, otherwise

3.26.3.7 bool isDH () const [inline]

Predicate used to determine whether this point is an element of (a multiplicative sub-group of) the group of nonzero integers modulo a large prime.

Returns:

true, if this Point’s parameters are those for (a multiplicative subgroup of) Zp∗false, otherwise

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 201: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.26 Point Class Reference 195

3.26.3.8 bool isEC () const [inline]

Predicate used to determine whether this Point is on an elliptic curve.

Returns:

true, if this Point’s parameters are those for an elliptic curvefalse, otherwise

3.26.3.9 bool isValid () const

Predicate used to test whether this Point lies on the underlying elliptic curve.

Returns:

true, if this Point is on the underlying curvefalse, otherwise

3.26.3.10 int length () const [inline]

Get the size in bytes of the largest integer that can be mapped into the current Abeliangroup.

Returns:

the maximum number of ∗bytes∗ that can be in a number as represented in thecurrent field/group/curve

Remarks:

This function is useful when you want to know how large a random number togenerate for certain cryptographic protocols (e.g., ECDSA signature generation).

3.26.3.11 int loadbin (int n, const char ∗ b)

Load an octet string into this Point.

Parameters:

n length of the octet string in bytesb pointer to the octet string

Returns:

the number of bytes used

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 202: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

196 Data Structure Documentation

3.26.3.12 num modulus2 () const [inline]

Get the order of the underlying finite field or order of the group.

Returns:

the modulus of the underlying finite field or order of the group

3.26.3.13 Point operator ∗ (const num & x) const

Multiply this Point by an integer.

Parameters:

x the multiple

Returns:

the specified multiple of this Point

3.26.3.14 bool operator!= (const Point & x) const [inline]

Predicate used to test the inequality of this Point with another one.

Parameters:

x the Point (i.e., group element) to which this one is to be compared

Returns:

true, if the two group elements disagreefalse, if the two Points are equal

3.26.3.15 bool operator!= (int n) const [inline]

Predicate used to test whether this Point differs from the identity element.

Parameters:

n = must be 0 or method asserts

Returns:

true, if this Point is not the identify elementfalse, otherwise

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 203: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.26 Point Class Reference 197

3.26.3.16 Point operator+ (const Point & y) const

Add another Point to this one.

Parameters:

y the Point to be added to this point

Returns:

the sum of this Point and y

3.26.3.17 Point operator- (const Point & y) const

Subtract another Point from this one.

Parameters:

y the Point to subtract from this point

Returns:

the difference of this Point and y

3.26.3.18 Point operator- () const

Get the additive inverse of this Point.

Returns:

the additive inverse of this Point

3.26.3.19 void operator= (const Point & x) [inline]

Assignment operator used to copy Points.

Parameters:

x the Point to copy into this one

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 204: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

198 Data Structure Documentation

3.26.3.20 void operator= (int n)

Assignment operator used to make this Point the identity element in the group.

Parameters:

n must be 0 (any other value will trigger an exception)

3.26.3.21 bool operator== (const Point & x) const [inline]

Predicate used to test the equality of this Point with another one.

Parameters:

x the Point (i.e., group element) to which this one is to be compared

Returns:

true, if the two group elements are equalfalse, if the two group elements disagree

3.26.3.22 bool operator== (int n) const

Predicate used to test whether this Point is the identity element in the group.

Parameters:

n must be 0 or method asserts

Returns:

true, if this Point is the identity element in its Abelian groupfalse, otherwise

3.26.3.23 void power (const Point & x, const num & y)

Assign an (unnormalized) multiple of a given Point to this one.

Parameters:

x the base Point

y the multiple of x to be assigned to this Point

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 205: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.26 Point Class Reference 199

3.26.3.24 int setcurve (const num & a, const num & b)

Specify the coefficients in the equation of an elliptic curve:

in char p: y 2 = x 3 + a x + b

in char 2: y 2 + x y = x 3 + a x 2 + b.

Parameters:

a the first coefficient

b the second coefficient

Returns:

0

3.26.3.25 int setgen (const num & g)

Specify a generator for the underlying Abelian group.

Parameters:

g a new generator for the underlying group

Returns:

0

3.26.3.26 T to (int opt = 0) const

Convert Point into an object of type T.

Parameters:

opt compression indicator: 0 = compressed, 1 = uncompressed

Returns:

an object of type T representing this Point

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 206: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

200 Data Structure Documentation

3.26.3.27 cdk::str tostr (int n = 0) const

Convert this Point into a str.

Parameters:

n a compression indicator: 0 = compressed, 1 = uncompressed

Returns:

a str representation of this Point

The documentation for this class was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 207: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.27 PRNG Class Reference 201

3.27 PRNG Class Reference

#include <rand.h>

Inheritance diagram for PRNG:

PRNG

Algorithm

Collaboration diagram for PRNG:

PRNG

Algorithm

SHA str

seedlastvalue

h

3.27.1 Detailed Description

Implementation of the NIST FIPS 186-2 Pseudorandom Number Generator.

Class PRNG implements the SHA-1 based pseudorandom number generator of FIPS186-2. The CDK also provides other pseudorandom number generators.

The most efficient way to use PRNG is:

• Instantiate a single PRNG object, and share it among multiple threads (usingappropriate mutexes to ensure that two threads don’t attempt to update the PRNGstate simultaneously).

• Call PRNG::add() when desired to provide additional entropy that supplementsthe system state information it gathers automatically.

• Use the optional callback parameter to the PRNG constructor to maintain a per-sistent copy of the PRNG state. Storing the copy in a disk file or in the Windowsregistry makes it available to multiple applications or threads. (Again, mutexes

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 208: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

202 Data Structure Documentation

should be used to ensure that no two threads attempt to update it at the sametime).

Usage flow:PRNG() // instantiate a new PRNG objectadd() // [optional] add additional entropyaddseed() // [optional] add entropy to the starting seedgens(), gen() // obtain as many pseudorandom bytes as required

Recommendations for strict FIPS 140-1 compliance:Only gens(), gen(), or getrand2() may be called to obtain a random numberused for cryptographic purposes. In other words, if you need to generatea symmetric key, do *not* use genbasic() or getrand1()!

Calling churn(), genbasic(), setSeed(), mytime1(), or getrand1() directlyis a violation of the FIPS 140-1 Security Policy for this CDK. Thesemethods should be treated as private.

Sample code illustrating the use of this class appears in the Cookbook section Pseudo-random Numbers.

NOTE: The CDK also provides two stateless random number generators via the globalfunctions getrand1() and getrand2(). getrand1() is a rather unsophisticated RNG inten-dend only for internal use in non-cryptographic applications; it is not FIPS 140-1 com-pliant. getrand1(n) returns an n-byte string obtained by repeated calls to Random32()(which maintains a rather pitiful 32-bit state vector). getrand2() is a somewhat fancierRNG that uses a temporary instantiation of PRNG.

3.27.2 References

NIST specified pseudorandom number generators in FIPS 186-2, FIPS 140-2Annex C, and NIST SP800-22.

Public Member Functions

• PRNG (int(∗f)(str &)=0)

Constructor.

• virtual ∼PRNG ()

Destructor that zeroizes internal state data.

• void add (int n, const char ∗s)

Update object’s internal state vector with additional entropy.

• str gens (int n)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 209: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.27 PRNG Class Reference 203

Get a specified number of random bytes and update object’s state vector.

• num gen (const num &modulus)Get a random integer less than a specified modulus and update object’s state vector.

Internal FunctionsThese functions are declared public, but are intended for internal use only. FIPS140-1 compliant applications may not use the methods and/or data members in thissection. These functions can be used to reproduce the example in NIST FIPS 186-2App. 5. (Function genbasic() is used by gens().)

• void setSeed (str &x)Specify a new seed value for this object; for internal use only.

• void addSeed (const str &x)Update internal seed value based on supplied input; for internal use only.

• void churn ()Update internal state vector using system state information as additional entropy.

• str genbasic (int iter)Basic pseudorandom number generator; for internal use only.

3.27.3 Constructor & Destructor Documentation

3.27.3.1 PRNG (int(∗)(str &) f = 0) [inline, explicit]

Constructor.

Parameters:

f an optional callback function which is to be passed each generated random num-ber. (A callback mechanism to provide additional entropy may be added inthe future.)

3.27.4 Member Function Documentation

3.27.4.1 void add (int n, const char ∗ s)

Update object’s internal state vector with additional entropy.

Parameters:

n the number of bytes in the input buffer

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 210: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

204 Data Structure Documentation

s a pointer to the input buffer

3.27.4.2 void addSeed (const str & x)

Update internal seed value based on supplied input; for internal use only.

Parameters:

x a str containing the data to be added to the seed.

Note:

The internal seed value is set to 0 by the constructor, so this can be used to set theseed to a specified value. Subsequent calls add x to the seed rather than resettingit. Since gens()/gen() call churn(), system state information is always factored inas additional entropy, so explicit calls to this method are not required.

3.27.4.3 void churn ()

Update internal state vector using system state information as additional entropy.

Remarks:

Calling churn() reseeds the PRNG with random system state information. Addi-tional, user-supplied entropy can be input by calling add(). Explicit calls to thesefunctions, however, are not really necessary as churn() is called automatically asrandom numbers are pulled from the PRNG object.

3.27.4.4 num gen (const num & modulus)

Get a random integer less than a specified modulus and update object’s state vector.

Parameters:

modulus the number that the generated random number must be less than

Returns:

a num containing a random number less than modulus

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 211: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.27 PRNG Class Reference 205

3.27.4.5 str genbasic (int iter)

Basic pseudorandom number generator; for internal use only.

Parameters:

iter a mechanism selector or interation count:

• 1 for the mechanism of FIPS 186-2, Appendix 3.1• 2 for the changes recommended by NIST on Aug. 2001• a positive integer larger than 2 results in a larger output string (see Re-

turns section for details)

Returns:

a str containing (iter ∗ 160) random bits, or an empty str if the CDK is in its harderror state

Note:

This function is for internal use only! It is used by class Key for DSA key genera-tion in compliance with FIPS 186-2.

3.27.4.6 str gens (int n)

Get a specified number of random bytes and update object’s state vector.

Parameters:

n the number of random bytes to generate

Returns:

a str containing n random bytes

3.27.4.7 void setSeed (str & x) [inline]

Specify a new seed value for this object; for internal use only.

Parameters:

x the new initial seed value

Note:

This function is for internal use only! It is used by class Key for DSA key genera-tion in compliance with FIPS 186-2.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 212: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

206 Data Structure Documentation

The documentation for this class was generated from the following file:

• rand.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 213: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.28 RC2 Struct Reference 207

3.28 RC2 Struct Reference

#include <rc2.h>

Inheritance diagram for RC2:

RC2

Algorithm

Collaboration diagram for RC2:

RC2

Algorithm

3.28.1 Detailed Description

Implementation of the RC2 symmetric block cipher.

RC2 is an 8-byte block cipher with a variable length key. It became popular in the late90’s principally due to its adaptability to past government export regulations: one caneasily limit the effective keysize to 40 bits. Today it is primarily used to decode oldPKCS#12 files and for other legacy purposes.

Usage flow:RC2() // instantiate a new RC2 objectinit() // specify direction, key, mode, and effective keysizecrypt() // perform the encrypt or decrypt operation

Bugs:the code does not properly handle 1-byte keys

Recommendations for strict FIPS 140-1 compliance:RC2 is not a FIPS approved algorithm, so the RC2 class should

*NOT* be used.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Symmetric Ciphers.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 214: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

208 Data Structure Documentation

3.28.2 References

RC2 is specified in RFC 2268, and in RFC 3217.

Public Types

• ENCRYPTcrypt() call performs encryption

• DECRYPTcrypt() call performs decryption

• enum dirs {

ENCRYPT,

DECRYPT }Direction flags.

Public Member Functions

• RC2 ()Constructor used to create an empty RC2 object.

• ∼RC2 ()Destructor. Calls clear().

• int init (enum dirs dir, int length, const char ∗key, const char ∗iv=0, intekb=1024)

Initialize the RC2 object.

• int crypt (int n, const char ∗in, char ∗out)Encrypt or decrypt a specified buffer.

• void clear ()Clear this object.

3.28.3 Member Enumeration Documentation

3.28.3.1 enum dirs

Direction flags.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 215: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.28 RC2 Struct Reference 209

Enumerator:

ENCRYPT crypt() call performs encryption

DECRYPT crypt() call performs decryption

3.28.4 Member Function Documentation

3.28.4.1 void clear ()

Clear this object.

Remarks:

All key components are zeroized.

3.28.4.2 int crypt (int n, const char ∗ in, char ∗ out)

Encrypt or decrypt a specified buffer.

Parameters:

n the number of bytes in the input and output buffers

in a pointer to the input buffer

out a pointer to the output buffer

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTR

3.28.4.3 int init (enum dirs dir, int length, const char ∗ key, const char ∗ iv = 0,int ekb = 1024)

Initialize the RC2 object.

Parameters:

dir a direction indicator: ENCRYPT or DECRYPT

length the length of key in bytes; usually 40 or 128

key a pointer to a buffer containing the key

iv either 0 (for ECB mode) or an 8-byte initialization vector (for CBC mode)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 216: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

210 Data Structure Documentation

ekb the number of effective key bits

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTR

Remarks:

If the expanded RC2 key has an effective key length greater than ekb, then it isreduced to an effective length of ekb bits).

The documentation for this struct was generated from the following file:

• rc2.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 217: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.29 RC4 Class Reference 211

3.29 RC4 Class Reference

#include <rc4.h>

Inheritance diagram for RC4:

RC4

Algorithm

Collaboration diagram for RC4:

RC4

Algorithm

3.29.1 Detailed Description

Implementation of the RC4 stream cipher.

The ISC implementation of RC4 is compatible with RSADSI RC4, and with the cipherthat the US State Dept. calls RC4; it is also known as "alleged RC4" and ARCFOUR.

Usage flow:RC4() // instantiate a new RC4 objectinit() // specify the keycrypt() // perform the encrypt or decrypt operation

Recommendations for strict FIPS 140-1 compliance:RC4 is not a FIPS approved algorithm, so the RC4 class should

*NOT* be used.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Symmetric Ciphers.

3.29.2 References

RC4 is specified and discussed in:

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 218: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

212 Data Structure Documentation

• RFC 2246

• IETF ID "Arcfour"

• J. Golic, "Linear statistical weakness of alleged RC4 keystream generator," Ad-vances in Cryptology, Proceedings Eurocrypt’97, LNCS 1233, W. Fumy, Ed.,Springer-Verlag, 1997, pp. 226–238.

• CipherSaber has an english language description of RC4 at:http://ciphersaber.gurus.com/faq.html#getrc4

• B. Schneier, Applied Cryptography, 2nd ed., John Wiley & Sons, 1996.

Public Member Functions

• RC4 ()Constructor. Calls init().

• ∼RC4 ()Destructor. Calls init().

• int init ()Initialize the RC4 object.

• int init (int len, const char ∗key)Initialize the RC4 object and load a new key.

• int add (int len, const char ∗b)Update the permutation controlling the internal pseudorandom number generator.

• int crypt (int len, const char ∗src, char ∗dest)Encrypt or decrypt a specified buffer.

• int gen ()Generate one pseudorandom byte.

3.29.3 Member Function Documentation

3.29.3.1 int add (int len, const char ∗ b)

Update the permutation controlling the internal pseudorandom number generator.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 219: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.29 RC4 Class Reference 213

Parameters:

len the length in bytes of the input buffer

b a pointer to the input buffer

Returns:

0 (success)CDK_ERROR_STATE CDK_INVALID_PTR

3.29.3.2 int crypt (int len, const char ∗ src, char ∗ dest)

Encrypt or decrypt a specified buffer.

Parameters:

len the length of the input and output buffers in bytes

src a pointer to the input buffer

dest a pointer to the output buffer

Returns:

0 (success)CDK_ERROR_STATE CDK_INVALID_PTR

3.29.3.3 int gen ()

Generate one pseudorandom byte.

Returns:

a single byte from the internal pseudorandom number generator.

3.29.3.4 int init (int len, const char ∗ key)

Initialize the RC4 object and load a new key.

Parameters:

len the length of key in bytes

key a pointer to the new key

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 220: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

214 Data Structure Documentation

Remarks:

All key material is reset, then add() is called to update the permutation controllingthe internal pseudorandom number generator.

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTR

3.29.3.5 int init ()

Initialize the RC4 object.

Returns:

0 (success)CDK_ERROR_STATE

Remarks:

This function resets the RC4 object to its initial state, zeroizing all key material.

The documentation for this class was generated from the following file:

• rc4.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 221: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.30 recinfo Struct Reference 215

3.30 recinfo Struct Reference

#include <asn.h>

3.30.1 Detailed Description

Lowest level data type used to process ASN.1 data.

Public Member Functions

Initializers

• int load (const str &x)Load entire PDU into this object.

• int scan (int n, const char ∗x)Parse data buffer into this object.

Inspectors

• double length () constGet the total length in bytes of the PDU in this object.

• int ilength () constGet total length of PDU in this object as an integer.

• int ibody () constGet size of PDU body in this object.

Predicates

• bool isNullTerminator () constPredicate used to determine whether this PDU is a null terminator.

3.30.2 Member Function Documentation

3.30.2.1 int ibody () const [inline]

Get size of PDU body in this object.

Returns:

length of PDU body (truncated to an integer)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 222: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

216 Data Structure Documentation

3.30.2.2 int ilength () const [inline]

Get total length of PDU in this object as an integer.

Returns:

total length of PDU as an int (i.e., possibly truncated)

3.30.2.3 double length () const [inline]

Get the total length in bytes of the PDU in this object.

Returns:

total length of PDU

3.30.2.4 int load (const str & x)

Load entire PDU into this object.

Parameters:

x the PDU to be loaded

Returns:

0 success1 cannot parse PDU2 inconsistent header info3 parsing error

3.30.2.5 int scan (int n, const char ∗ x)

Parse data buffer into this object.

Parameters:

n the length in bytes of the input buffer

x a pointer to the input buffer

Returns:

0 (success)2 if PDU header is incomplete3 if PDU cannot be parsed or is longer than the 2∧48 byte limit

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 223: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.30 recinfo Struct Reference 217

The documentation for this struct was generated from the following file:

• asn.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 224: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

218 Data Structure Documentation

3.31 RSA Class Reference

#include <pk.h>

Inheritance diagram for RSA:

RSA

Algorithm

Collaboration diagram for RSA:

RSA

Algorithm num

dmods1dmodr1

pqexpo

dmodq1qinvmodpdmodp1

pqinvmodrpqrsd

pqrinvmods

FParms

p

Parameters Nat

v

primeinvbc

3.31.1 Detailed Description

Implementation of RSA-based cryptographic schemes.

Code samples illustrating the use of class RSA can be found in the Cookbook sectionHandling Public and Private Keys.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 225: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.31 RSA Class Reference 219

3.31.2 References

The RSA public key cryptosystem is specified in:

• RFC 2437 (PKCS #1 v2.0)

• RFC 3447 (PKCS #1 v2.1)

• FIPS 186-2

• ANSI X9.31-1998

• ANSI X9.44

• IEEE 1363-2000

Public Types

• pkcs1 = 1

Perform PKCS#1 v1.5 compliant operations.

• x931 = 2

Perform ANSI x9.31 compliant operations.

• pss = 3

Use PSS (PKCS#1 v2.1).

• enum {

pkcs1 = 1,

x931 = 2,

pss = 3 }

Standards compliance flags.

Public Member Functions

• RSA ()

Constructor used to create an empty RSA object (PKCS#1 with 2 primes).

• virtual ∼RSA ()

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 226: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

220 Data Structure Documentation

Destructor.

• int check () constCheck the consistency of the public and private key components in this object.

• int loadpub (const num &expo1, const num &pq1)Load a (raw) RSA public key into this object.

• int loadpriv (const num &p1)Load (raw) RSA private key into this object (as a single prime factor of the modulus).

• int loadpriv (const num &p1, const num &q1)Load a (raw) RSA private key into this object (as a pair of prime factors of the modu-lus).

• str asn1private () constGet this object’s ASN.1 DER-encoded private key.

• int loadasn1private (const str &b1)Load an ASN.1 DER-encoded private key.

• int loadpub (const str &pubk)Load an ASN.1 DER-encoded public key.

• int genpub ()Generate a public key based on the private key in this object.

• int setup ()Derive PKCS#1 RSA private key components from the prime factors of the modulus.

• int encrypt (const num &m, num &x) constEncrypt a specified buffer.

• int decrypt (const num &c, num &x) constDecrypt a specified buffer.

• int sign (const num &hash, const num &random, num &sig, int nHashType)const

Sign a specified message digest.

• bool hasPrivate () constPredicate used to test whether this object contains a private key.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 227: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.31 RSA Class Reference 221

• bool hasPublic () const

Predicate used to test whether this object contains a public key.

• void clear ()

Clear this object.

3.31.3 Member Enumeration Documentation

3.31.3.1 anonymous enum

Standards compliance flags.

Enumerator:

pkcs1 Perform PKCS#1 v1.5 compliant operations.

x931 Perform ANSI x9.31 compliant operations.

pss Use PSS (PKCS#1 v2.1).

3.31.4 Member Function Documentation

3.31.4.1 str asn1private () const

Get this object’s ASN.1 DER-encoded private key.

Returns:

a str containing this object’s ASN.1 DER-encoded private key (in the clear!)

3.31.4.2 int check () const

Check the consistency of the public and private key components in this object.

Returns:

0 (success, i.e., the key is OK)CDK_NO_KEYCDK_KEYPAIR_INCONSISTENT, if the public key doesn’t match the privatekey

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 228: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

222 Data Structure Documentation

3.31.4.3 void clear (void) [inline]

Clear this object.

Remarks:

Modifies: size and public key are zeroized; other components are zeroized by theirown destructors when the object is destroyed.

3.31.4.4 int decrypt (const num & c, num & x) const

Decrypt a specified buffer.

Parameters:

c a num representing the ciphertext to decrypt

x a num to receive the plaintext output

Returns:

0 (success)CDK_ERROR_STATE

3.31.4.5 int encrypt (const num & m, num & x) const

Encrypt a specified buffer.

Parameters:

m a num representing the message to encrypt

x a num to receive the ciphertext output

Returns:

0 (success)CDK_ERROR_STATE

3.31.4.6 int genpub ()

Generate a public key based on the private key in this object.

Returns:

0

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 229: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.31 RSA Class Reference 223

3.31.4.7 bool hasPrivate () const [inline]

Predicate used to test whether this object contains a private key.

Returns:

true, if this object contains a private keyfalse, otherwise

3.31.4.8 bool hasPublic () const [inline]

Predicate used to test whether this object contains a public key.

Returns:

true, if this object contains a public keyfalse otherwise

3.31.4.9 int loadasn1private (const str & b1)

Load an ASN.1 DER-encoded private key.

Parameters:

b1 the ASN.1 DER-encoded private key to be loaded

Returns:

0 (success)CDK_PARSE_ERRORCDK_INVALID_KEY_TOO_MANY_PRIMES

Remarks:

Only private keys containing 2, 3, or 4 primes are supported.

3.31.4.10 int loadpriv (const num & p1, const num & q1) [inline]

Load a (raw) RSA private key into this object (as a pair of prime factors of the modu-lus).

Parameters:

p1 the first prime

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 230: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

224 Data Structure Documentation

q1 the second prime

Returns:

0

3.31.4.11 int loadpriv (const num & p1) [inline]

Load (raw) RSA private key into this object (as a single prime factor of the modulus).

Parameters:

p1 the private key to load into this object.

Returns:

0

Remarks:

This call clears the object’s public key.

3.31.4.12 int loadpub (const str & pubk)

Load an ASN.1 DER-encoded public key.

Parameters:

pubk the ASN.1 DER-encoded RSA public key to be loaded

Returns:

0 (success)CDK_NO_KEYCDK_KEYPAIR_INCONSISTENTCDK_KEY_INVALID

3.31.4.13 int loadpub (const num & expo1, const num & pq1)

Load a (raw) RSA public key into this object.

Parameters:

expo1 the RSA exponent

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 231: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.31 RSA Class Reference 225

pq1 the RSA modulus

Returns:

0

3.31.4.14 int setup ()

Derive PKCS#1 RSA private key components from the prime factors of the modulus.

Returns:

0 (success)

Remarks:

Modifies: d, dmodp1, dmodq1, qinvmodp, dmodr1, pqinvmodr, dmods1, andpqrinvmods.

3.31.4.15 int sign (const num & hash, const num & random, num & sig, intnHashType) const [inline]

Sign a specified message digest.

Parameters:

hash a num containing the hash value to be signed

random unused (provided for template compatability with Key)

sig the output buffer to receive the signature

nHashType algorithm id: hSHA1 or hMD5 (FIPS 140-1 compliant applicationsmust use hSHA1)

Returns:

0 (success)CDK_ERROR_STATE

The documentation for this class was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 232: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

226 Data Structure Documentation

3.32 SHA Class Reference

#include <sha.h>

Inheritance diagram for SHA:

SHA

Algorithm

Collaboration diagram for SHA:

SHA

Algorithm

3.32.1 Detailed Description

Implementation of the NIST Secure Hash Algorithm (SHA/SHA-1), FIPS 180-1.

Usage flow:SHA() // construct a new SHA objectadd() // call as many times as necessary to process datafinal() // finalize message digest computationresult() // obtain resulting hash value

Recommendations for strict FIPS 140-1 compliance:As long as you do not use SHA-0, all public data members and methods ofclass SHA can be used by an application requiring FIPS 140-1 compliance.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Message Digest Functions.

3.32.2 References

SHA-1 is specified in:

• FIPS 180-2

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 233: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.32 SHA Class Reference 227

• ANSI X9.30 Part 2

• ISO/IEC 10118-3:1998

Public Member Functions

• SHA (int version=1)Constructor used to create an initialized SHA object for SHA (i.e., SHA-0) or SHA-1.

• ∼SHA ()Destructor. Calls clear();.

• int add (char c)Update message digest computation with a single byte.

• int add (int bytes, const char ∗buf)Update message digest computation with a buffer.

• int add (int nbits, int b)Update message digest computation with a specified number of bits.

• int final (void)Finalize the message digest computation.

• void finalstore (void)finalstore:

• const char ∗ result (void) constGet a pointer to the final message digest.

• int length () constGet the length in bytes of a message digest.

• int blocksize () constGet the algorithm block size.

• double count64 () constGet the number of bytes hashed so far.

• template<class T> T to () constGet a type T representation of the message digest.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 234: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

228 Data Structure Documentation

• str tostr () const

Get a str representation of the message digest.

• void reset (int version=1)

Reset this SHA object. Calls clear().

• void resetk (void)

resetk:

• void clear (void)

Clear this object, zeroizing and/or reinitializing all internal data.

3.32.3 Constructor & Destructor Documentation

3.32.3.1 SHA (int version = 1) [inline, explicit]

Constructor used to create an initialized SHA object for SHA (i.e., SHA-0) or SHA-1.

Parameters:

version indicator: 0 for SHA-0, 1 for SHA-1

Remarks:

SHA-1 is the default, if no version is specified. SHA-0 should not be used!

3.32.4 Member Function Documentation

3.32.4.1 int add (int nbits, int b)

Update message digest computation with a specified number of bits.

Parameters:

nbits the number of bits in b to be hashed

b an int containing the bits to be hashed

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 235: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.32 SHA Class Reference 229

Remarks:

This function MUST BE CALLED LAST AND ONLY ONCE when hashing along bit string. Call add(char) or add(int, const char∗) on your data until youhave less than one byte remaining. Then call this function. Example: add(4,0x50)causes ’0x0101’ to be hashed.

Note:

FIPS 140-1 testing of the CDK was performed for SHA-1 in BYTE mode, but notin BIT mode.

3.32.4.2 int add (int bytes, const char ∗ buf)

Update message digest computation with a buffer.

Parameters:

bytes the number of bytes in the input bufferbuf a pointer to the input buffer

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTR

3.32.4.3 int add (char c)

Update message digest computation with a single byte.

Parameters:

c the byte to be hashed

Returns:

0 (success)CDK_ERROR_STATE

3.32.4.4 int blocksize () const [inline]

Get the algorithm block size.

Returns:

64.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 236: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

230 Data Structure Documentation

3.32.4.5 double count64 () const [inline]

Get the number of bytes hashed so far.

Returns:

the number of bytes processed by an add() function since the last clear.

3.32.4.6 int final (void)

Finalize the message digest computation.

Returns:

0 (success)CDK_ERROR_STATE

3.32.4.7 void finalstore (void)

finalstore:

Note:

This function is intended for internal use only. It does not return a final messagedigest, but rather an intermediate value required by class PRNG.

Returns:

0 (success)CDK_ERROR_STATE

3.32.4.8 int length () const [inline]

Get the length in bytes of a message digest.

Returns:

20

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 237: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.32 SHA Class Reference 231

3.32.4.9 void reset (int version = 1)

Reset this SHA object. Calls clear().

Parameters:

version indicates which version of SHA to perform: <= 0 for SHA, >= 1 forSHA-1

3.32.4.10 void resetk (void)

resetk:

Remarks:

This function is provided for internal DSA use only.

3.32.4.11 const char∗ result (void) const

Get a pointer to the final message digest.

Returns:

a pointer to the 16-byte message digest(NULL, if the CDK is in its hard error state)

3.32.4.12 T to () const [inline]

Get a type T representation of the message digest.

Returns:

an object of type T representating the message digest

3.32.4.13 str tostr () const

Get a str representation of the message digest.

Returns:

a str containing the string representation of the message digest.

The documentation for this class was generated from the following file:

• sha.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 238: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

232 Data Structure Documentation

3.33 SHA2 Class Reference

#include <sha.h>

Inheritance diagram for SHA2:

SHA2

Algorithm

Collaboration diagram for SHA2:

SHA2

Algorithm

3.33.1 Detailed Description

Implementation of the Extended NIST Secure Hash Algorithms (SHA-256/-384/-512),FIPS 180-2.

Usage flow:SHA2() // construct a new SHA2 objectadd() // call as many times as necessary to process datafinal() // finalize message digest computationresult() // obtain resulting hash value

Recommendations for strict FIPS 140-1 compliance:All public data members and methods of the SHA2 class can be usedby an application requiring FIPS 140-1 compliance.

Sample code illustrating the use of this class appears in the Cookbook section Usingthe Message Digest Functions.

3.33.2 References

SHA-256/-384/-512 are specified in:

• FIPS 180-2

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 239: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.33 SHA2 Class Reference 233

• original NIST Specifications

Public Member Functions

• SHA2 (int version)

Constructor used to create a new object initialized for SHA-256, -384 or -512.

• ∼SHA2 ()

Destructor. Calls clear();.

• int add (char c)

Update message digest computation with a single byte.

• int add (int bytes, const char ∗buf)

Update message digest computation with a buffer.

• int final (void)

Finalize the message digest computation.

• const char ∗ result (void) const

Get a pointer to the final message digest.

• int length () const

Get the length in bytes of a message digest.

• int blocksize () const

Get the algorithm block size.

• template<class T> T to () const

Get a type T representation of the message digest.

• str tostr () const

Get a str representation of the message digest.

• void clear (void)

clear

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 240: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

234 Data Structure Documentation

3.33.3 Constructor & Destructor Documentation

3.33.3.1 SHA2 (int version) [inline, explicit]

Constructor used to create a new object initialized for SHA-256, -384 or -512.

Parameters:

version indicator: 2 for SHA-256, 3 for SHA-384, 5 (or any other value) for SHA-512

3.33.4 Member Function Documentation

3.33.4.1 int add (int bytes, const char ∗ buf)

Update message digest computation with a buffer.

Parameters:

bytes the number of bytes in the input buffer

buf a pointer to the input buffer

Returns:

0 (success)CDK_ERROR_STATECDK_INVALID_PTR

3.33.4.2 int add (char c) [inline]

Update message digest computation with a single byte.

Parameters:

c the byte to be hashed

Returns:

0 (success)CDK_ERROR_STATE

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 241: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.33 SHA2 Class Reference 235

3.33.4.3 int blocksize () const [inline]

Get the algorithm block size.

Returns:

the algorithm’s block size in bytes (64 or 128)

3.33.4.4 void clear (void)

clear

Remarks:

Modifies: clear() called to initialize the object. vers doesn’t change.

3.33.4.5 int final (void)

Finalize the message digest computation.

Returns:

0 (success)CDK_ERROR_STATE

3.33.4.6 int length () const

Get the length in bytes of a message digest.

Returns:

the expected number of output bytes (32, 48, or 64)

3.33.4.7 const char∗ result (void) const

Get a pointer to the final message digest.

Returns:

a pointer to the message digest(NULL, if the CDK is in its hard error state)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 242: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

236 Data Structure Documentation

3.33.4.8 T to () const [inline]

Get a type T representation of the message digest.

Returns:

an object of type T representating the message digest

3.33.4.9 str tostr () const

Get a str representation of the message digest.

Returns:

a str containing the string representation of the message digest.

The documentation for this class was generated from the following file:

• sha.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 243: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.34 Signature Class Reference 237

3.34 Signature Class Reference

#include <pk.h>

Collaboration diagram for Signature:

Signature

num

rs

FParms

p

Parameters Nat

v

primeinvbc

3.34.1 Detailed Description

Data type used for digital signature operations.

Public Member Functions

Destructor

• virtual ∼Signature ()Destructor.

Object Reuse and Initialization

• void clear ()Clear this object.

• int init (const Key &k)Initialize this object based on a specified key.

• int load (const str &x, int isRaw=0)Load a raw binary or ASN.1 DER-encoded signature into this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 244: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

238 Data Structure Documentation

Predicates

• bool isRSA () constPredicate used to test whether this object contains an RSA signature.

Conversions

• template<class T> T to () constConvert this object into an object of type T.

• str toraw () constConvert this object into a str containing a raw signature.

• asn toasn1 () constConvert this object into a ASN.1 DER-encoded str object.

3.34.2 Member Function Documentation

3.34.2.1 void clear (void) [inline]

Clear this object.

Remarks:

Internal signature components are zeroized.

3.34.2.2 int init (const Key & k)

Initialize this object based on a specified key.

Parameters:

k a key whose parameters are inspected and used to initialize this object.

Returns:

0

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 245: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.34 Signature Class Reference 239

3.34.2.3 bool isRSA () const [inline]

Predicate used to test whether this object contains an RSA signature.

Returns:

true, if this is an RSA signature0, otherwise

3.34.2.4 int load (const str & x, int isRaw = 0)

Load a raw binary or ASN.1 DER-encoded signature into this object.

Parameters:

x ASN.1 DER-encoded signature or binary raw signature

isRaw 0 if x is ASN.1 encoded1 if you know x is RAW (function will try RAW anyway, if ASN.1 decodingfails)

Returns:

0 (success)1, if the signature cannot be loadedCDK_INVALID_SIGNATURE, if the signature was successfully parsed butdoesn’t validate against this object’s public key.

3.34.2.5 T to () const

Convert this object into an object of type T.

Returns:

a class T representation of the signature (typically a binary string)

3.34.2.6 asn toasn1 () const

Convert this object into a ASN.1 DER-encoded str object.

Returns:

a str containing an ASN.1 DER-encoded signature

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 246: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

240 Data Structure Documentation

3.34.2.7 str toraw () const

Convert this object into a str containing a raw signature.

Returns:

a str containing a raw signature

The documentation for this class was generated from the following file:

• pk.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 247: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.35 Signer Struct Reference 241

3.35 Signer Struct Reference

#include <cert.h>

Collaboration diagram for Signer:

Signer

asn

messageDigest2signature1

sMIMECapabilitesreceiptRequestmessageDigest1

oidpkreturnemail

str

3.35.1 Detailed Description

Data type used for CMS digital signature operations.

Sample code illustrating the use of this class to create signed CMS PDUs appears inthe Cookbook section IETF Cryptographic Message Syntax (CMS).

Public Member Functions

• void clear ()

Clear this object.

• int load (const str &b)

Load this object with signer information.

• int make (const str &digest, const str &cert, const Key &k, const num &rand, str&b)

Create a CMS SignerInfo PDU using a specified key.

• int make2 (const str &digest, tokenop &t1, str &b)

Create a CMS SignerInfo PDU using a signing callback.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 248: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

242 Data Structure Documentation

3.35.2 Member Function Documentation

3.35.2.1 int make (const str & digest, const str & cert, const Key & k, const num& rand, str & b)

Create a CMS SignerInfo PDU using a specified key.

Parameters:

digest the message digest to be signed

cert the signer’s certificate

k the signer’s key (SHA-1 hashing and PKCS#1 padding must already be speci-fied)

rand an pseudorandom seed required for non-deterministic signatures

b an output buffer for the CMS SignerInfo PDU

Returns:

0 success1 signature operation failed

3.35.2.2 int make2 (const str & digest, tokenop & t1, str & b)

Create a CMS SignerInfo PDU using a signing callback.

Parameters:

digest the message digest to be signed

t1 the signature callback function

b an output buffer for the CMS SignerInfo PDU

Returns:

0 success2 no callback function specified in t1 6 signature callback failed

Remarks:

Upon return the output buffer contains a SignerInfo PDU as specified in RFC 3852,section 5.3.

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 249: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 243

3.36 str Struct Reference

#include <str.h>

Inheritance diagram for str:

str

asn

3.36.1 Detailed Description

Class str is somewhat similar to the STL std::string type.

str objects created by the supplied constructors have null terminators so that they can beused as normal C strings. (For example, they can be passed to strlen().) The terminatingnull is not considered part of the str object or counted in its length.

For efficiency, the implementation of str uses shared memory and performs garbagecollection. Hence the following caveats:

1. A str object returned by a function might not have a null terminator.

2. Do not directly modify a str object via a pointer to its character buffer unless youare sure that no other str objects share that buffer.

3. The amount of memory allocated to a non-empty str object can exceed the size ofthe string stored in it, but there is no memory allocated when the length is zero.

Call str::purify() to guarantee a null terminator and an unshared character buffer.

Warnings: str::str(const char ∗p) may truncate binary data copied from p so be verycareful in situations like this:

char x[10] = "sdf\0asld\n";str y = x; // y only gets "sdf\0" and the rest of x is discarded!

Instead, use:

str y(10,x);

or

str y = str(10,x);

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 250: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

244 Data Structure Documentation

Also, the concatenation logic does not preserve null terminators. In other words, becareful about:

str a("United "), b("States"); // both null terminatedstr c = a + b; // a,c possibly not null terminateda.purify(); // a is null terminated again

Recommendations for strict FIPS 140-1 compliance:

All applications should use str objects for storing keys as the class’sdestructor will zeroize the object’s memory when it is explicitlydestroyed or goes out of scope. If the application does not use the CDK’sstr class for storing keys, the application must guarantee that the memoryused to store keys is zeroized.

Class str contains no methods that perform or use cryptographic operations.

Public Types

• npos = -1

= -1 (invalid byte offset or character not found)

• enum { npos = -1 }

For compatibility with the standard string class.

Public Member Functions

Constructors and Destructors

• str ()Constructor used to create an empty str object.

• str (const str &x)Copy constructor.

• str (int len)Constructor used to create an object of a specified length.

• str (int len, const char ∗p, int max=0)Constructor used to create an object with specified data.

• str (const char ∗p)Constructor used to create an object containing an ASCII text string.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 251: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 245

• ∼str ()Destructor, calls clear() to zeroize all data fields.

Inspectors and Manipulators

• int length () constGet the length in bytes of this object’s data.

• char ∗ constptr () const

Get a (const) pointer to the kth byte in this object’s internal data buffer.

• char ∗ rawptr (int k=0) constGet a pointer to the kth byte in this object’s internal data buffer.

• const char ∗ c_str ()Null-terminate this object and get a (const) pointer to its internal data buffer.

• void makeunique ()Ensure that this object’s character buffer is not shared by another object.

• void nullterminate ()Null-terminate this object.

• void purify ()Null-terminate this object and ensure that its character buffer is not shared byanother str object.

• str skip (int k) constCreate a new object containing all but the leftmost k bytes of this object.

• str trunc (int k) constTruncate this str object.

• bool isText () constPredicate used to determine if this object contains printable ASCII text.

String Operators

• operator const char ∗ () constGet a pointer to this object’s internal data buffer; operator version.

• str operator= (const str &x)Assignment operator used to duplicate a str object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 252: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

246 Data Structure Documentation

• bool operator== (const str &y) constOperator used to test equality of two str objects.

• bool operator!= (const str &y) constOperator used to test inequality of two str objects.

• int operator+ () constOperator used to obtain the length in bytes of this object’s data.

• int operator[ ] (int k) constGet the k-th byte in this object’s data buffer.

• char & operator[ ] (int k)Get a reference to the k-th byte in this object’s data buffer.

• str operator+ (const str &y) constCreate a new str object by concatenating a specified str object onto this one.

• void operator+= (const str &y)Concatenate a specified str object onto this one.

• void operator∧= (const str &y)XOR two str object together.

Conversion Functions

• str tohex (int withprefix=0) constConvert tbis object’s data to a string of ASCII hex digits.

• str tobase64 (int rfcpad=1) constBase64 encode this object.

• str tobin64 () constBase64 decode this object.

• double todouble () constConvert to double.

• long tolong () constConvert to long.

• str towrap (int width) constLine wrap the data in this object.

Substrings, Search, and Replace

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 253: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 247

• str substr (int offset, int length) constExtract a substring from this str object.

• int find (char ch, int offset=0) constFind the first instance of a specified character in this str object.

• str replace (int pos, int n, const str &z)Replace substring with string.

• str insert (int pos, const str &z)Insert substring.

• str erase (int pos, int n)Erase substring.

3.36.2 Member Enumeration Documentation

3.36.2.1 anonymous enum

For compatibility with the standard string class.

Enumerator:

npos = -1 (invalid byte offset or character not found)

3.36.3 Constructor & Destructor Documentation

3.36.3.1 str (int len) [inline, explicit]

Constructor used to create an object of a specified length.

Parameters:

len the size of buffer to preallocate in bytes

3.36.3.2 str (int len, const char ∗ p, int max = 0) [inline, explicit]

Constructor used to create an object with specified data.

Parameters:

len the length in bytes of the data bufferp a pointer to the buffer containing data for the new stringmax the length of this object’s data buffer (if more than len bytes is desired)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 254: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

248 Data Structure Documentation

3.36.3.3 str (const char ∗ p)

Constructor used to create an object containing an ASCII text string.

Parameters:

p a pointer to a null-terminated ASCII text string

3.36.4 Member Function Documentation

3.36.4.1 str erase (int pos, int n) [inline]

Erase substring.

Parameters:

pos starting offset

n number of bytes to erase

Returns:

the modified str object

3.36.4.2 int find (char ch, int offset = 0) const

Find the first instance of a specified character in this str object.

Parameters:

ch the character to be found

offset a starting point for the search

Returns:

the index of the specified character in the str object or, if the character is not found,npos

3.36.4.3 str insert (int pos, const str & z) [inline]

Insert substring.

Parameters:

pos starting offset

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 255: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 249

z string to be inserted into this object

Returns:

the modified str object

3.36.4.4 bool isText () const

Predicate used to determine if this object contains printable ASCII text.

Returns:

true, if every character in this object has an ASCII code between 8 and 127false, otherwise

3.36.4.5 int length () const [inline]

Get the length in bytes of this object’s data.

Returns:

length of this object in bytes

3.36.4.6 operator const char ∗ () const [inline]

Get a pointer to this object’s internal data buffer; operator version.

Returns:

a pointer to (the beginning of) this object’s internal data buffer

Remarks:

Use of this member function is dangerous. Remember that a str object’s internaldata buffer may be shared by other str objects, and that it will be de-allocated whenthe str object goes out of scope.

3.36.4.7 bool operator!= (const str & y) const [inline]

Operator used to test inequality of two str objects.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 256: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

250 Data Structure Documentation

Parameters:

y the str object to which this one is to be compared

Returns:

true, if y is not equivalent to this str objectfalse, otherwise.

3.36.4.8 str operator+ (const str & y) const [inline]

Create a new str object by concatenating a specified str object onto this one.

Parameters:

y the str object to be appended to this one

Returns:

a str object containing the contents of this str followed by the contents of y

3.36.4.9 int operator+ () const [inline]

Operator used to obtain the length in bytes of this object’s data.

Returns:

length of this object’s data

3.36.4.10 str operator= (const str & x)

Assignment operator used to duplicate a str object.

Parameters:

x the str object to assign to this object

Reimplemented in asn.

3.36.4.11 bool operator== (const str & y) const

Operator used to test equality of two str objects.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 257: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 251

Parameters:

y the str object to which this one is to be compared

Returns:

true, if y is equivalent to this str objectfalse, otherwise.

3.36.4.12 ]

char& operator[ ] (int k) [inline]

Get a reference to the k-th byte in this object’s data buffer.

Parameters:

k the index of the byte to be dereferenced

Returns:

a reference to the k-th byte in this object’s data buffer

Remarks:

This operator facilitates s[1] = ’C’ type assignments.Use of Use of this member function is dangerous. Remember that a str object’sinternal data buffer may be shared by other str objects.

3.36.4.13 ]

int operator[ ] (int k) const [inline]

Get the k-th byte in this object’s data buffer.

Parameters:

k the index of the byte to return

Returns:

the k-th byte in this object’s data buffer

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 258: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

252 Data Structure Documentation

3.36.4.14 void operator∧= (const str & y)

XOR two str object together.

Parameters:

y the str to be XOR’ed into this one

3.36.4.15 char∗ rawptr (int k = 0) const [inline]

Get a pointer to the kth byte in this object’s internal data buffer.

Parameters:

k a starting offset into this object’s data buffer

Returns:

a pointer to the kth byte in this object’s internal data buffer

Remarks:

Use of this member function is dangerous. Remember that a str object’s internaldata buffer may be shared by other str objects.

3.36.4.16 str replace (int pos, int n, const str & z) [inline]

Replace substring with string.

Parameters:

pos starting offset

n number of characters to replace

z replacement string

Returns:

the modified str object

3.36.4.17 str skip (int k) const

Create a new object containing all but the leftmost k bytes of this object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 259: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 253

Parameters:

k the number of bytes to be skipped

Returns:

a str consisting of all but the first k bytes of this object

3.36.4.18 str substr (int offset, int length) const

Extract a substring from this str object.

Parameters:

offset the starting index of the substringlength the length of the substring to be extracted

Returns:

a str containing a substring of the specified length starting at the specified index

3.36.4.19 str tobase64 (int rfcpad = 1) const

Base64 encode this object.

Parameters:

rfcpad padding indicator: use 1 to ensure that the encoded length is a multiple of4, 0 if you don’t care

Returns:

a str containing the base64-encoded data

Remarks:

A padding indicator of 1 results in the output str being printable encoded accordingto RFC 1113 and RFC 1421

3.36.4.20 str tobin64 () const

Base64 decode this object.

Returns:

a str containing the (binary) data obtained by base64 decoding this object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 260: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

254 Data Structure Documentation

3.36.4.21 double todouble () const [inline]

Convert to double.

Returns:

a double representation of this string

3.36.4.22 str tohex (int withprefix = 0) const

Convert tbis object’s data to a string of ASCII hex digits.

Parameters:

withprefix prefix indicator: 1 to prepend ’0x’ to the output string, 0 to omit thisprefix

Returns:

a str containing an ASCII hexadecimal representation of the data in this object

3.36.4.23 long tolong () const

Convert to long.

Returns:

a signed integer from this string, using up to 4 bytes

3.36.4.24 str towrap (int width) const

Line wrap the data in this object.

Parameters:

width the desired line length

Returns:

a new str with newlines inserted every ’width’ characters

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 261: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.36 str Struct Reference 255

3.36.4.25 str trunc (int k) const

Truncate this str object.

Parameters:

k the number of bytes to retain

Returns:

a str containing only the initial k bytes of this object

The documentation for this struct was generated from the following file:

• str.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 262: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

256 Data Structure Documentation

3.37 TLS Struct Reference

#include <tls.h>

Collaboration diagram for TLS:

TLS

party

sc

RC4

rc4i

Algorithm

DES AES str

userinputchainhandshake

master_secretseed

userchaindn

session_idpremaster

temprandcryptmaccerivbuf

desi aesi

3.37.1 Detailed Description

Data type used to implement SSLv2/TLS. For details, see RFC 2246.

Sample code illustrating the use of this class appears in the Cookbook section Imple-menting a Simple TLS Client.

Public Member Functions

Constructor

• TLS ()Constructor.

Object Reuse and Initialization

• void clear ()Reset TLS object.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 263: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.37 TLS Struct Reference 257

• int setcipher (int cipher, int minor)Specify cipher suite and minor TLS version number.

• void setrand (const str &r1, const str &r2, const str &r3, double now)Seed pseudorandom number generation.

• int load (const Chain &a)Load chain of certificates for client authentication.

Inspectors

• str version () constGet current TLS version number.

• int parse (str &rec, str &rest) constExtract top-level record from server buffer.

Communications Processing Functions

• int dorecs ()Process communication records between client and server.

Encryption and Decryption

• str wrap (str data)Encrypt data buffer (with MAC).

• int unwrap (str data, str &plain)Dencrypt data buffer (and strip MAC).

Predicates

• bool isBad () constPredicate to test object’s error state.

Data Fields

• party cclient

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 264: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

258 Data Structure Documentation

• party s

server

• str dn

list of CA DNs accepted by server for client authentication

• int lasterror

explanation of last non-zero return code

• TokenSignCallback sign

callback for client authentication via token

• void ∗ tokeninfoptr

additional data for signature callback

3.37.2 Member Function Documentation

3.37.2.1 int dorecs ()

Process communication records between client and server.

Returns:

0 did nothing1 success2 error/warning3 fatal error

Remarks:

Invokes signature callback when client authentication is required during initialhandshake with server.

3.37.2.2 int load (const Chain & a)

Load chain of certificates for client authentication.

Parameters:

a chain of certificates to be loaded

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 265: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.37 TLS Struct Reference 259

Returns:

0 success

Remarks:

Certificates must be supplied in the following order: end-entity, intermediate CAcertificates, root certificate.

3.37.2.3 int parse (str & rec, str & rest) const

Extract top-level record from server buffer.

Parameters:

rec buffer in which to place the top-level record (prior to unwrapping)rest buffer in which to place the remaining data from the server buffer

Returns:

0 success1 incomplete input record2 error

3.37.2.4 int setcipher (int cipher, int minor)

Specify cipher suite and minor TLS version number.

Parameters:

cipher ID of desired cipher suite:• 0x04 = RC4/MD5• 0x05 = RC4/SHA1• 0x09 = DES• 0x0a = TDES• 0x2f = AES-128• 0x35 = AES-256

minor TLS version number

Returns:

0 success1 invalid cipher suite ID

Remarks:

If server supports TDES but not requested cipher suite, subsequent dorecs() callswill fall back to TDES; otherwise dorecs() calls will fail.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 266: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

260 Data Structure Documentation

3.37.2.5 void setrand (const str & r1, const str & r2, const str & r3, double now)[inline]

Seed pseudorandom number generation.

Parameters:

r1 46-byte seed (for premaster secret)

r2 28-byte seed (for client portion of master secret)

r3 extra 20-byte seed (for client authentication using DSA or ECDSA)

now current time (provides additional entropy for client portion of master secret)

3.37.2.6 int unwrap (str data, str & plain)

Dencrypt data buffer (and strip MAC).

Parameters:

data buffer to be decrypted

plain output buffer for plaintext

Returns:

0 success

3.37.2.7 str version () const [inline]

Get current TLS version number.

Returns:

string representation of current TLS version (1 = TLS, aka SSL v3.1)

3.37.2.8 str wrap (str data)

Encrypt data buffer (with MAC).

Parameters:

data buffer to be encrypted

Returns:

a string representation of the ciphertext.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 267: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.37 TLS Struct Reference 261

The documentation for this struct was generated from the following file:

• tls.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 268: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

262 Data Structure Documentation

3.38 tokenop Struct Reference

#include <cert.h>

Collaboration diagram for tokenop:

tokenop

str

passwordsharedwrappedrand

privatekeyephemeralparameters

cercipherresult

publickeyhash

certid

serialissuer

cid

3.38.1 Detailed Description

Data type used by callbacks to do private key operations, possibly on a hardware token.

Public Member Functions

• tokenop ()

Constructor.

• bool hasCallback () const

Predicate used to determine whether a callback has been registered.

• int keysize () const

Get size of symmetric key in bytes (for CAPI).

Data Fields

• int format

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 269: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

3.38 tokenop Struct Reference 263

archive type (0 for sa5, 1 for CMS)

• int sigformat

signature type (0 for SHA1, 1 for TLS, 2 for SHA256, 3 for SHA384, 5 for SHA512)

• int isSig

operation identifier: 0 for decrypt, 1 for sign

• void ∗ tokeninfoptr

pointer to opaque data passed to callback

• str wrapped

wrapped session key

• str hash

message digest to be signed

• str cipher

cipher (for CAPI)

• str cer

certificate (if available)

• certid cid

certificate ID (if decrypting CMS)

• str parameters

DL parameters.

• str ephemeral

ephemeral key for DL operations

• str shared

DH parameter.

• str publickey

public key (if available)

• str privatekey

private key (p8 or p12)

• str password

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 270: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

264 Data Structure Documentation

password for private key

• str randrandom value for DL operations (unused for RSA)

• str resultreturn value provided by callback function

• TokenCallback cbcallback function (NULL if none is registered)

The documentation for this struct was generated from the following file:

• cert.h

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 271: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

Chapter 4

File Documentation

4.1 aes.h File Reference

4.1.1 Detailed Description

Interface definition for class AES.

Implemented in aes.c.

AES (also known as "Rijndael") is specified in FIPS 197.

Namespaces

• namespace cdk

Data Structures

• class AESImplementation of the NIST Advanced Encryption Standard ("AES"), FIPS 197.

Page 272: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

266 File Documentation

4.2 alg.h File Reference

4.2.1 Detailed Description

Algorithm base class for system and error state tracking.

All algorithm classes in the CDK are derived from this base class so that they can detectwhen the CDK enters a "hard" error state. Once error is set to true, the only way toreset it to false is to reload the DLL.

Implemented in alg.c.

Namespaces

• namespace cdk

Data Structures

• class AlgorithmBase class for tracking algorithm errors and internal system states.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 273: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.3 asn.h File Reference 267

4.3 asn.h File Reference

4.3.1 Detailed Description

Interface definition for low-level ASN.1 functions.

Implemented in asn1.cpp.

Namespaces

• namespace cdk

Data Structures

• struct recinfoLowest level data type used to process ASN.1 data.

• struct DateData type used for date and time processing.

• struct asnInternal data type used for ASN.1 BER/DER encoding/decoding.

Typedefs

• typedef double cdk::TimeTData type used to extend UNIX time format.

Enumerations

• enum cdk::tags {

cdk::Bool = 0x01,

cdk::Int = 0x02,

cdk::Bit = 0x03,

cdk::Oct = 0x04,

cdk::Obj = 0x06,

cdk::Asc = 0x13,

cdk::Asc0C = 0x0C,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 274: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

268 File Documentation

cdk::Asc14 = 0x14,

cdk::Asc16 = 0x16,

cdk::Asc1A = 0x1A,

cdk::T_Date17 = 0x17,

cdk::T_Date = 0x18,

cdk::Unicode = 0x1E,

cdk::Seq = 0x30,

cdk::Set = 0x31 ,

cdk::VarStr = 0x0B,

cdk::VarInt = 0x1F,

cdk::VarNum = 0x0D,

cdk::VarDate = 0x0E,

cdk::TagOption = 0x0F,

cdk::BitTrunc = -3 }ASN.1 tags for simple types and aliases for various BER/DER encoding bytes.

Functions

• _cdkpub TimeT cdk::timegmt ()Get the current time (GMT) in UNIX format.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 275: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.4 cdk.h File Reference 269

4.4 cdk.h File Reference

4.4.1 Detailed Description

Primary CDK header file, includes headers for all library modules.

Defines Class ISC_CDK which contains the self-tests.

Implemented in cdk.c.

Namespaces

• namespace cdk

Data Structures

• class ISC_CDKBase class for FIPS 140-1 on-demand self-tests, error state tracking, and convenienceutilities.

Functions

• _cdkpub num cdk::loaddec (const char ∗s)Convert an ASCII string of decimal digits to the corresponding num.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 276: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

270 File Documentation

4.5 cdkerr.h File Reference

4.5.1 Detailed Description

Definitions of CDK 7.0 error codes.

Adapted from the CDSA 1.2 specification submitted to the OpenGroup by IBM andIntel.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 277: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.6 cert.h File Reference 271

4.6 cert.h File Reference

4.6.1 Detailed Description

Interfaces for certificate processing and related ASN.1 functions.

Defines structs/classes: Data, DName, Cert, Chain, CRL, Signer, CMS1

The standard algorithms implemented here are not in the FIPS-approved class, but arespecified in various ISO/IEC and IETF publications.

Requires str.h, pk.h

Implemented in cert.c.

Functions performing cryptographic operations are:checksign()checksignhash()makep8() - if this fails, check Algorithm::isErrorState()

to see if CDK is in the hard error state.parsep8()parsep10()checkcert()CRL::check()

All other methods and functions are merely data manipulation tools for dealingwith ASN.1 objects.

Recommendations for strict FIPS 140-1 compliance:All classes/methods defined in this file may be used in an application claimingFIPS 140-1 complaince with the exception of specifying hash types and/or algorithms.Hash type must be hSHA1 as that is the only FIPS approved hash algorithm. You cannotuse *makep12* or *parsep12* as the PKCS #12 specific requires RC2 be used for the outerencryption and TDES for encrypting the private key.

Namespaces

• namespace cdk

Data Structures

• struct DNameData type used for representing and processing X.500 distinguished names.

• struct CertData type used for encoding and decoding individual X.509 certificates.

• struct ChainData type used for processing X.509 certificate chains.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 278: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

272 File Documentation

• struct CRLData type used for creating and processing certificate revocation lists.

• struct certidData type used to detect matching certificates.

• struct tokenopData type used by callbacks to do private key operations, possibly on a hardwaretoken.

• struct SignerData type used for CMS digital signature operations.

• struct CMS1Data type used for in-memory PKCS #7 operations (RFC 3852 CMS).

Typedefs

• typedef int(CALLBACK ∗) cdk::TokenDecryptCallback (tokenop &)Callback type for decryption operations.

• typedef int(CALLBACK ∗) cdk::TokenSignCallback (tokenop &)Callback type for signature operations.

• typedef int(CALLBACK ∗) cdk::TokenVerifyCallback (tokenop &)Callback type for signature validation.

Functions

• _cdkpub int cdk::parsedname (const str &dn, str &ASCII, int opt=0)Parse an ASN.1 encoded DN into a printable string.

• _cdkpub int cdk::parsesign (const str &cer, asn &body, asn &oid, asn &sig, intrecode_der=0)

Parse the signature out of an ASN.1 encoded certificate.

• _cdkpub str cdk::makesign (const str &body, const str &oid, const str &sig)Create an X.509 certificate (or CRL) by combining its body with an issuer’s signature.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 279: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.6 cert.h File Reference 273

• _cdkpub num cdk::makep1 (int htype, const num &hvalue, int n)

Pad a message digest value according to PKCS#1v1.5 (for signing).

• _cdkpub int cdk::parsep1 (const str &b, int &htype, asn &hvalue)

Parse a PKCS#1v1.5 padded message digest.

• _cdkpub str cdk::makep7 (const Chain &chn)

Create an ASN.1 encoded PKCS#7 PDU containing a set of certificates.

• _cdkpub int cdk::parsep7 (const str &b, Chain &chn)

Parse an ASN.1 encoded PKCS#7 PDU containing one or more certificates.

• _cdkpub str cdk::makep8 (const str &oid, const str &prv, const str &pwd)

Create an ASN.1 encoded PKCS#8 PDU containing an encrypted private key.

• _cdkpub int cdk::parsep8 (const str &p8, const str &pwd, asn &oid, asn &prv)

Decrypt and parse an ASN.1 encoded PKCS#8 PDU containing an encrypted privatekey.

• _cdkpub str cdk::makep10raw (const str &dn, const str &oid, const str &pub,const str &attributes)

Create an ASN.1 encoded PKCS#10 certificate request.

• _cdkpub int cdk::parsep10 (const str &p10, asn &dn, asn &oid, asn &pub, asn&attributes)

Parse an ASN.1 encoded PKCS#10 certificate request.

• _cdkpub int cdk::parse_crmf (const str &req, asn &dn, asn &oid, asn &pub, asn&attributes)

Parse an ASN.1 encoded CRMF PDU.

• _cdkpub str cdk::make_cmmf (const Chain &chn, int requestid)

Create a Netscape CMMF PDU.

• _cdkpub str cdk::makep12 (const str &cer, const str &oid, const str &prv, conststr &pwd, const str &frname, const str &id)

Create an ASN.1 encoded PKCS#12 PDU.

• _cdkpub int cdk::parsep12 (const str &p12, const char ∗pwd, Chain &chn, asn&oid, asn &prv, asn &crl)

Decrypt and parse an ASN.1 encoded PKCS#12 PDU containing an encrypted privatekey.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 280: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

274 File Documentation

• _cdkpub int cdk::checkcert (const str &certissuer, const str &certsubject)Validate one ASN.1 encoded certificate against another.

• _cdkpub int cdk::checksign (const str &cer, const str &oidhash, const str &msg,const str &sig)

Validate an ASN.1 encoded digital signature over a specified message.

• _cdkpub int cdk::checksignhash (const str &cer, const num &h, const str &sig)Validate an ASN.1 encoded digital signature over a specified hash value.

• typedef cdk::int (CALLBACK ∗TokenCallback)(tokenop &)General callback type.

• _cdkpub str cdk::make_ocsp_req (const str &caCert, const str &subCert, conststr &nonce)

Create an OCSP request.

• _cdkpub int cdk::check_ocsp (const str &req, const str &resp, asn &signinfo,TimeT &revTime, asn &certs, asn &dn)

Check an OCSP response.

• _cdkpub int cdk::check_signinfo (const str &cer, const str &signinfo)Check an OCSP response.

• _cdkpub str cdk::asn1ber_to_der (const asn &ber)Convert a BER-encoded (indefinite length encoding) to a DER-encoded PDU.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 281: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.7 crc.h File Reference 275

4.7 crc.h File Reference

4.7.1 Detailed Description

Interface definition for class CRC.

Implemented in crc.c using the the hash function interface.

The IEEE 32-bit CRC is used in Autodin II, IEEE 802.3 (Ethernet), ISO/IEC-3309(HDLC), and RFC 1662 (PPP), RFC 1952 (GZIP), and elsewhere.

Namespaces

• namespace cdk

Data Structures

• class CRCImplementation of the IEEE 32-bit CRC.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 282: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

276 File Documentation

4.8 des.h File Reference

4.8.1 Detailed Description

Interface definition for class DES (DES, TDES, and variants; FIPS 46-3/81).

DES is specified in: FIPS 46-2 (1994), ANSI X3.92-1981, FIPS 74, ISO/IEC8731:1987.

DES modes of operation are specified in: FIPS 81 (1980), ISO/IEC 8372

Triple DES (TDES) is specified in FIPS 46-3 (1999), ANSI x9.17-1985, and X9.52-1998.

TDES modes of operation are specified in NIST SP 800-20 and SP800-38A.

DESX was first suggested by R. Rivest and has been analyzed by J. Killian and P.Rogaway and by RSA Security Inc.

Class DES is implemented in des.c.

Namespaces

• namespace cdk

Data Structures

• class DESImplementation of the NIST Data Encryption Standard (DES, TDES, and variants),FIPS 46-3/81.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 283: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.9 ees.h File Reference 277

4.9 ees.h File Reference

4.9.1 Detailed Description

Interface definition for class EES ("Skipjack," FIPS 185).

Implemented in ees.c.

Namespaces

• namespace cdk

Data Structures

• class EESImplementation of the NIST EES ("Skipjack"), FIPS 185.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 284: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

278 File Documentation

4.10 hmac.h File Reference

4.10.1 Detailed Description

Template definition for HMAC-SHA1 and HMAC-MD5 (RFC 2104).

Notes: The HMAC template is explicitly instantiated (for those systems whose com-pilers don’t support the template approach) only for SHA-1 and MD5. For the smaeportability reasons, these instantiations do not call DoHash<>() .

4.10.2 References

HMAC is documented in:

• FIPS 198

• RFC 2104

• ANSI x9.71

• ISO/IEC FDIS 9797-2

Namespaces

• namespace cdk

Functions

• template<class T> str cdk::HMAC (const str &key, const str &msg)Compute an HMAC over a specified message using a specified key.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 285: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.11 md2.h File Reference 279

4.11 md2.h File Reference

4.11.1 Detailed Description

Interface definition for class MD2 (RFC 1319).

Implemented in md2.c.

Namespaces

• namespace cdk

Data Structures

• class MD2Implementation of the RFC 1319 MD2 message digest.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 286: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

280 File Documentation

4.12 md5.h File Reference

4.12.1 Detailed Description

Interface definition for class MD5 (RFC 1321).

Implemented in md5.c.

Namespaces

• namespace cdk

Data Structures

• class MD5Implementation of the RFC 1321 MD5 message digest.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 287: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.13 oid.h File Reference 281

4.13 oid.h File Reference

4.13.1 Detailed Description

Definitions of various OIDs.

Implemented in oid.c.

Namespaces

• namespace cdk

Functions

• _cdkpub str cdk::A2O (const str &strDotted)Convert human readable OID’s in dotted notation to binary equivalent for encoding.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 288: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

282 File Documentation

4.14 parms.h File Reference

4.14.1 Detailed Description

Interface definitions for various group and field parameters.

Implemented in Parms.c.

Recommendations for strict FIPS 140-1 compliance:This class is a helper class in that it contains pre-generated DSA and ECDSAparameters so that DSA/ECDSA key pairs may be generated without firstgenerating parameters. For FIPS 140-1 Compliance an application should onlyuse the DSA parameters in DSA_Parms or the NIST approvped curves inNIST_Curves. If an application generates their own parameters (either DSA withcdk::DSA_GenerateParameters() or ECDSA with their own algorithms) they mayuse this class to convert the parameters to the ASN.1 OID form required bythe Key class by first calling Parms::check() and then Parms::oid().

Namespaces

• namespace cdk

Data Structures

• struct GroupData

Data type used to store parameters for particular Abelian groups.

Enumerations

• enum cdk::DSAParms {

cdk::FIPSEXAMPLE = 0,

cdk::ISCDSA512 = 1,

cdk::ISCDSA768 = 2,

cdk::ISCDSA1024 = 3,

cdk::ISCDSA2048 = 4,

cdk::ISCDSA4096 = 5 }

Parameter IDs for DSA.

• enum cdk::NISTCurves {

cdk::NISTP192 = 0,

cdk::NISTP224 = 1,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 289: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.14 parms.h File Reference 283

cdk::NISTP256 = 2,

cdk::NISTP384 = 3,

cdk::NISTP521 = 4,

cdk::NISTK163 = 5,

cdk::NISTB163 = 6,

cdk::NISTK233 = 7,

cdk::NISTB233 = 8,

cdk::NISTK283 = 9,

cdk::NISTB283 = 10,

cdk::NISTK409 = 11,

cdk::NISTB409 = 12,

cdk::NISTK571 = 13,

cdk::NISTB571 = 14 }Parameter IDs for NIST FIPS 186-2 elliptic curves; SECG and ANSI X.9.62 aliasesare also provided below.

Variables

• GroupData const cdk::DSA_Parms [6]• GroupData const cdk::NIST_Curves [15]• GroupData const cdk::ANSI_Curves [1]• GroupData const cdk::MicrosoftDRM

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 290: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

284 File Documentation

4.15 pass.h File Reference

4.15.1 Detailed Description

Interface definition for class Password (FIPS 181).

Implemented in pass.c.

Namespaces

• namespace cdk

Data Structures

• class PasswordImplementation of the NIST FIPS 181 Automated Password Generator.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 291: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.16 pk.h File Reference 285

4.16 pk.h File Reference

4.16.1 Detailed Description

Interface definitions for CDK classes implementing high-precision integer arithmeticand high-level public key operations.

The most important classes and structs defined in pk.h are described in the followingtable:

Class is defined in: an object of this typerepresents:

num num.c an integer or an elementof a finite field

Nat num.c a natural numberFParms num.c a set of finite field

parametersGParms num.c a set of parameters for a

finite Abelian groupPoint point.c & num.c an element of a finite

Abelian groupKey key.c & cert.c a public and/or private

keyRSA cert.c & key.c an RSA public and/or

private keySignature cert.c & key.c a digital signature

The following classes perform all ’high-level’ cryptographic operations:

• Key

• RSA

• Signature

while the following ’low-level classes’ provide the requisite collection of underlyingarithmetical operations:

• num

• Nat

• FParms

• GParms

• Point

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 292: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

286 File Documentation

Note: Using the low-level classes directly may violate the CDK’s Security Policy foroperating in FIPS 140-1 mode. These classes may be used to store information, butshould not be used to perform cryptographic operations that are the equivalent of keypair generation. (You may, however, use class Point as illustrated in the Cookbooksection Diffie-Hellman Key Agreement.)

Recommendations for strict FIPS 140-1 compliance:

Classes Key, RSA, and Signature (together with DSA_Generate_Parameters())may be used to implement all common public key operations. While thedirect use of the other classes defined in pk.h is not prohibited for FIPS140-1 compliance (unless explicitly stated below), ISC generallyrecommends against it. (See Note above.)

This code is covered by US patents:5,274,707 - Modular Exponentiation and Reduction Device and Method5,373,560 - Partial Modular Reduction Method

Namespaces

• namespace cdk

Data Structures

• class Nat

Data type used to represent elements of various algebraic objects.

• struct Parameters

Base class for arithmetic parameters (used to define various algebraic structures).

• class FParms

Data type used to specify arithmetic parameters for various rings and fields.

• struct num

Implementation of the arithmetic in various groups, rings, and fields.

• class GParms

Data type used to specify arithmetic parameters for various groups, including ellipticcurves.

• class Point

Data type used to represent the elements of, and abstract the operations in, variousAbelian groups, including elliptic curves.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 293: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.16 pk.h File Reference 287

• class RSA

Implementation of RSA-based cryptographic schemes.

• class Signature

Data type used for digital signature operations.

• struct Key

Class Key is the principal data type used for public and private keys and all relatedcryptographic operations.

Typedefs

• typedef Nat ∗ cdk::nat

pointer to a Nat

• typedef Nat const ∗ cdk::cnat

const pointer to a Nat

• typedef unsigned int cdk::nword

basic word type

• typedef nword ∗ cdk::nwordp

pointer to a nword

• typedef nword const ∗ cdk::cnwordp

const pointer to a nword

Enumerations

• enum cdk::hashes {

cdk::hNone,

cdk::hMD2 = 1,

cdk::hMD4 = 2,

cdk::hMD5 = 3,

cdk::hSHA1 = 4,

cdk::hSHA256 = 5,

cdk::hSHA384 = 6,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 294: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

288 File Documentation

cdk::hSHA512 = 7,

cdk::hSHA224 = 8 }Algorithm IDs for various hash functions (values are consistent with MS CAPI)

• enum cdk::groupsIDs for various groups/algorithms (for internal use only).

Functions

• _cdkpub str cdk::genkeyp5 (const str &pwd, const str &salt, int iter, int n)Generate a (symmetric) key from a password as per PKCS#5.

• _cdkpub str cdk::genkeyp12 (const str &pwd, const str &salt, int n, int iter, intid)

Generate a (symmetric) key from a password as per PKCS#12.

• _cdkpub int cdk::DSA_GenerateParameters (const str &seed, int nq, int np, num&q, num &p, num &g, int &counter, int start=0, int h=2, int v=1)

Generate DSA parameters as per FIPS 186-2.

• _cdkpub int cdk::rsadecrypt (const num &pq, const num &d, const num &input,str &x)

Raises input to the power d, mod pq, and strips pkcs1 padding.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 295: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.17 rand.h File Reference 289

4.17 rand.h File Reference

4.17.1 Detailed Description

Interface definition for class PRNG (FIPS 186-2) and other random number generators.

Implemented in rand.c.

Namespaces

• namespace cdk

Data Structures

• class PRNGImplementation of the NIST FIPS 186-2 Pseudorandom Number Generator.

Functions

• _cdkpub double cdk::mytime1 ()Get system time.

• _cdkpub str cdk::getrand1 (int n)Get a str object containing a specified number of pseudorandom bytes.

• _cdkpub str cdk::getrand2 (int n)Get a str object containing a specified number of pseudorandom bytes.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 296: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

290 File Documentation

4.18 rc2.h File Reference

4.18.1 Detailed Description

Interface definition for class RC2 (RFC 2268).

Implemented in r2.c.

Namespaces

• namespace cdk

Data Structures

• struct RC2Implementation of the RC2 symmetric block cipher.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 297: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.19 rc4.h File Reference 291

4.19 rc4.h File Reference

4.19.1 Detailed Description

Interface defintion for class RC4 (RFC 2246).

Implemented in rc4.c.

Namespaces

• namespace cdk

Data Structures

• class RC4Implementation of the RC4 stream cipher.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 298: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

292 File Documentation

4.20 sha.h File Reference

4.20.1 Detailed Description

Interface definitions for classes SHA and SHA2 (FIPS 180-2).

Two classes are defined. SHA which is implemented in sha.c and SHA2 which isimplemented in sha2.c

Namespaces

• namespace cdk

Data Structures

• class SHAImplementation of the NIST Secure Hash Algorithm (SHA/SHA-1), FIPS 180-1.

• class SHA2Implementation of the Extended NIST Secure Hash Algorithms (SHA-256/-384/-512),FIPS 180-2.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 299: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

4.21 str.h File Reference 293

4.21 str.h File Reference

4.21.1 Detailed Description

Types for handling strings and various cryptographic PDUs.

Implemented in str.c.

Namespaces

• namespace cdk

Data Structures

• struct strClass str is somewhat similar to the STL std::string type.

Functions

• template<class T> void cdk::operator+= (T &t, const str &x)Operator template used to add() a str object to an object of type T.

• template<class T> str cdk::tostr2 (const T &t)Template used to convert an object of type T into a str object.

• template<class T> str cdk::DoHash (const str &x, int v=1)Template used to hash a str object using a message digest of type T.

• _cdkpub str cdk::hex (const char ∗hexstr)Create a str object by parsing a specified string of hex digits.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 300: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

294 File Documentation

4.22 tls.h File Reference

4.22.1 Detailed Description

Interface definition for the SSLv3/TLS support routines. Implemented in tls.c.

Sample code illustrating use of the TLS class appears in the Cookbook section Imple-menting a Simple TLS Client.

Namespaces

• namespace cdk

Data Structures

• struct partyInternal data type used by the implementation of class TLS to encapsulate variouscryptographic operations.

• struct TLSData type used to implement SSLv2/TLS. For details, see RFC 2246.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 301: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

Chapter 5

Cookbook

5.1 Using the Symmetric Ciphers

This section provides several code samples for encrypting and decrypting arbitrary databuffers using the symmetric ciphers provided by the CDK.

The AES, TDES, and EES examples illustrate the processing of a single block of data.Obviously, one can process successive blocks by placing the crypt() call within a whileor for loop. In practice, however, when using these block ciphers you’ll need to padout your data to a multiple of the cipher’s block size. Further information on paddingappears in the section Padding Before Encryption at the bottom of this page.

The sample code fragments provided in this section

• AES Encryption/Decryption, ECB Mode

• AES Encryption/Decryption, CBC Mode

• TDES Encryption/Decryption, ECB Mode

• TDES Encryption/Decryption, CBC Mode

• EES Encryption/Decryption, ECB Mode

• EES Encryption/Decryption, CBC Mode

• RC2 Encryption/Decryption, ECB Mode

• RC2 Encryption/Decryption, CBC Mode

• RC4 Encryption/Decryption

all implement the following pseudocode:

Page 302: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

296 Cookbook

1. generate a random session key of the proper length

2. create an instance of the desired cipher object

3. initialize the cipher object for encryption

4. encrypt a single block of plaintext

5. clear the cipher object

6. reinitialize the cipher object for decryption

7. decrypt the ciphertext block

5.1.1 AES Encryption/Decryption, ECB Mode

// generate a random 192-bit (24-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(24);

// instantiate an AES object; initialize it to perform ECB encryptioncdk::AES aesi;aesi.init(AES::ENCRYPT, +strKey, strKey.c_str());

// encrypt a block of plaintextchar *pbuf ="0123456789abcdef"; // sample plaintextchar cbuf[16]; // output buffer for ciphertextaesi.crypt(16, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the AES object to perform decryptionaesi.clear();aesi.init(AES::DECRYPT, +strKey, strKey.c_str());

// decrypt a block of ciphertextchar obuf[16]; // buffer for plaintextaesi.crypt(16, cbuf, obuf); // obuf now contains copy of plaintext

5.1.2 AES Encryption/Decryption, CBC Mode

// generate a random 192-bit (24-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(24);cdk::str strIV = prngi.gens(16); // need a 16-byte IV for AES-CBC

// instantiate an AES object; initialize it to perform CBC encryptioncdk::AES aesi;aesi.init(AES::ENCRYPT, +strKey, strKey.c_str(), AES::CBC, strIV.c_str());

// encrypt a block of plaintextchar *pbuf ="0123456789abcdef"; // sample plaintextchar cbuf[16]; // output buffer for ciphertextaesi.crypt(16, pbuf, cbuf); // cbuf now contains ciphertext

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 303: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.1 Using the Symmetric Ciphers 297

// reinitialize the AES object to perform decryptionaesi.clear();aesi.init(AES::DECRYPT, +strKey, strKey.c_str(), AES::CBC, strIV.c_str());

// decrypt a block of ciphertextchar obuf[16]; // buffer for plaintextaesi.crypt(16, cbuf, obuf); // obuf now contains copy of plaintext

5.1.3 TDES Encryption/Decryption, ECB Mode

// generate a random 192-bit (24-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(24);

// instantiate a DES object; initialize it to perform TDES-ECB encryptioncdk::DES desi;desi.init(DES::ENCRYPT, +strKey, strKey.c_str(), DES::ALG_TDES);

// encrypt a block of plaintextchar *pbuf ="01234567"; // sample plaintextchar cbuf[8]; // output buffer for ciphertextdesi.crypt(8, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the DES object to perform decryptiondesi.clear();desi.init(DES::DECRYPT, +strKey, strKey.c_str(), DES::ALG_TDES);

// decrypt a block of ciphertextchar obuf[8]; // buffer for plaintextdesi.crypt(8, out, obuf); // obuf now contains copy of plaintext

5.1.4 TDES Encryption/Decryption, CBC Mode

// generate a random 192-bit (24-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(24);cdk::str strIV = prngi.gens(8); // need an 8-byte IV for TDES-CBC

// instantiate a DES object; initialize it to perform TDES-CBC encryptioncdk::DES desi;desi.init(DES::ENCRYPT, +strKey, strKey.c_str(), DES::ALG_TDES, DES::CBC, strIV.c_str());

// encrypt a block of plaintextchar *pbuf ="01234567"; // sample plaintextchar cbuf[8]; // output buffer for ciphertextdesi.crypt(8, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the DES object to perform decryptiondesi.clear();desi.init(DES::DECRYPT, +strKey, strKey.c_str(), DES::ALG_TDES, DES::CBC, strIV.c_str());

// decrypt a block of ciphertextchar obuf[8]; // buffer for plaintextdesi.crypt(8, out, obuf); // obuf now contains copy of plaintext

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 304: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

298 Cookbook

5.1.5 EES Encryption/Decryption, ECB Mode

// generate a random 80-bit (10-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(10);

// instantiate an EES object; initialize it to perform ECB encryptioncdk::EES eesi;eesi.init(EES::ENCRYPT, +strKey, strKey.c_str());

// encrypt a block of plaintextchar *pbuf ="01234567"; // sample plaintextchar cbuf[8]; // output buffer for ciphertexteesi.crypt(8, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the EES object to perform decryptioneesi.clear();eesi.init(EES::DECRYPT, +strKey, strKey.c_str());

// decrypt a block of ciphertextchar obuf[8]; // buffer for plaintexteesi.crypt(8, out, obuf); // obuf now contains copy of plaintext

5.1.6 EES Encryption/Decryption, CBC Mode

// generate a random 80-bit (10-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(10);cdk::str strIV = prngi.gens(8); // need an 8-byte IV for EES-CBC

// instantiate an EES object; initialize it to perform CBC encryptioncdk::EES eesi;eesi.init(EES::ENCRYPT, +strKey, strKey.c_str(), EES::CBC, strIV.c_str());

// encrypt the datachar *pbuf ="01234567"; // sample plaintextchar cbuf[8]; // output buffer for ciphertexteesi.crypt(8, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the EES object to perform decryptioneesi.clear();eesi.init(EES::DECRYPT, +strKey, strKey.c_str(), EES::CBC, strIV.c_str());

// decrypt a block of ciphertextchar obuf[8]; // buffer for plaintexteesi.crypt(8, out, obuf); // obuf now contains copy of plaintext

5.1.7 RC2 Encryption/Decryption, ECB Mode

// generate a random 128-bit (16-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(16);

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 305: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.1 Using the Symmetric Ciphers 299

// instantiate an RC2 object; initialize it to perform ECB encryptioncdk::RC2 rc2i;rc2i.init(RC2::ENCRYPT, +strKey, strKey.c_str());

// encrypt a block of plaintextchar *pbuf ="01234567"; // sample plaintextchar cbuf[8]; // output buffer for ciphertextrc2i.crypt(8, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the RC2 object to perform decryptionrc2i.clear();rc2i.init(RC2::DECRYPT, +strKey, strKey.c_str());

// decrypt a block of ciphertextchar obuf[8]; // buffer for plaintextrc2i.crypt(8, out, obuf); // obuf now contains copy of plaintext

5.1.8 RC2 Encryption/Decryption, CBC Mode

// generate a random 128-bit (16-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(16);cdk::str strIV = prngi.gens(8); // need an 8-byte IV for RC2-CBC

// instantiate an RC2 object; initialize it to perform CBC encryptioncdk::RC2 rc2i;rc2i.init(RC2::ENCRYPT, +strKey, strKey.c_str(), strIV.c_str());

// encrypt a block of plaintextchar *pbuf ="01234567"; // sample plaintextchar cbuf[8]; // output buffer for ciphertextrc2i.crypt(8, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the RC2 object to perform decryptionrc2i.clear();rc2i.init(RC2::DECRYPT, +strKey, strKey.c_str(), strIV.c_str());

// decrypt a block of ciphertextchar obuf[8]; // buffer for plaintextrc2i.crypt(8, out, obuf); // obuf now contains copy of plaintext

5.1.9 RC4 Encryption/Decryption

// generate a random 128-bit (16-byte) session keycdk::PRNG prngi;cdk::str strKey = prngi.gens(16);

// instantiate an RC2 object and initialize itcdk::RC4 rc4i;rc4i.init(+strKey, strKey.c_str());

// encrypt the plaintextchar *pbuf ="01234567abc"; // sample plaintext (arbitrary length)char cbuf[11]; // output buffer for ciphertext

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 306: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

300 Cookbook

rc4i.crypt(11, pbuf, cbuf); // cbuf now contains ciphertext

// reinitialize the RC2 object to perform decryptionrc4i.init(+strKey, strKey.c_str());

// decrypt the ciphertextchar obuf[11]; // buffer for plaintextrc4i.crypt(11, out, obuf); // obuf now contains copy of plaintext

5.1.10 Padding Before Encryption

In nearly all modes, the block ciphers AES, EES, DES, and RC2 require that the lengthof their inputs be a multiple of their respective block sizes. If the input data is notalready of the appropriate length, you must pad it. (The only exceptions to this rule isCFB8 mode, since AES, EES, and TDES are essentially stream ciphers in this mode.)

NOTE: RC4 is a stream cipher so padding is not required.

A standard padding mechanism is specified in PKCS #5. It is relatively straightforwardto implement, but since it is not exposed in the CDK the code and a use case areprovided here. Note that you only need to pad the last block of your data.

cdk::str makep5(const cdk::str x, int n=8){

// pad according to PKCS #5 (RFC 1423), n = 8 or 16cdk::str y = x;int len = n * ((+x + n)/n);cdk::str fill = cdk::single(n - (+x % n));while ( +y < len ) y += fill;return y;

}

cdk::str parsep5(const cdk::str x, int n=8){

// strip padding according to PKCS #5 (RFC 1423)cdk::str strRetVal = cdk::str(0);if ( +x != 0 ){int pad = x[+x-1];if ( !(pad < 1 || pad > n) )strRetVal = x.trunc(+x-pad);

}return strRetVal;

}

int main(){int i;cdk::str strIn = "short";cdk::str strPadded;char szOut[16];cdk::PRNG prngi;cdk::str strKey = prngi.gens(24); // 16 = 128-bit, 24 = 192-bit, 32 = 256-bit// instantiate a AES object to perform encryption.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 307: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.1 Using the Symmetric Ciphers 301

cdk::AES aesi;i = aesi.init(AES::ENCRYPT, +strKey, strKey.c_str());if (i) return i;if (+strIn % 16 != 0) // padding required{

strPadded = makep5(strIn, 16);}// encrypt the datachar out[16];i = aesi.crypt(16, strPadded.c_str(), out);if (i) return i;

// Decrypt it and unpadi = aesi.init(AES::DECRYPT, +strKey, strKey.c_str());if (i) return i;i = aesi.crypt(16, out, out);cdk::str strOut(16, out);strOut = parsep5(strOut, 16);if (strOut != strIn) return 1; // errorreturn 0;

}

For information concerning the objects used here see:

• cdk::AES

• cdk::DES

• cdk::EES

• cdk::RC2

• cdk::RC4

• cdk::PRNG

The next topic is Using the Message Digest Functions.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 308: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

302 Cookbook

5.2 Using the Message Digest Functions

This section illustrates the use of the CDK’s message digest (hashing) functions:

• NIST Secure Hash Algorithm (SHA-1), FIPS 180-1

• NIST Secure Hash Algorithms (SHA-256/394/512), FIPS 180-2

• MD2 Message Digest, RFC 1319

• MD5 Message Digest, RFC 1321

• IEEE 32-bit CRC

• HMAC

Each hashing example implements the following pseudocode:

1. instantiate an object of the desired message digest type

2. process the message data to be hashed

3. finalize the message digest computation

4. extract and print the final message digest

5.2.1 NIST Secure Hash Algorithm (SHA-1), FIPS 180-1

cdk::SHA sha; // instantiate a SHA object (does SHA-1 by default)sha.add(9, "test data"); // process the message data (repeat as needed)sha.final(); // finalize the computation

// extract the digest value from the object and pretty-print itcdk::str digest; // output string for hash valuedigest.assign(sha.length(),sha.result());printf("the SHA-1 hash of the message is %s\n", digest.tohex().c_str());

5.2.2 NIST Secure Hash Algorithms (SHA-256/394/512), FIPS180-2

cdk::SHA2 sha2(2); // initialize a SHA2 object to perform SHA-256// (or use 3 for SHA-394, 5 for SHA-512)

sha2.add(9, "test data"); // process the message data (repeat as needed)sha2.final(); // finalize the computation

// extract the digest value from the object and pretty-print itcdk::str digest; // output string for hash valuedigest.assign(sha2.length(),sha2.result());printf("the SHA-256 hash of the message is %s\n", digest.tohex().c_str());

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 309: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.2 Using the Message Digest Functions 303

5.2.3 MD2 Message Digest, RFC 1319

cdk::MD2 md2; // instantiate an MD2 objectmd2.add(9, "test data"); // process the message data (repeat as needed)md2.final(); // finalize the computation

// extract the digest value from the object and pretty-print itcdk::str digest; // output string for hash valuedigest.assign(md2.length(),md2.result());printf("the MD2 hash of the message is %s\n", digest.tohex().c_str());

5.2.4 MD5 Message Digest, RFC 1321

cdk::MD5 md5; // instantiate an MD5 objectmd5.add(9, "test data"); // process the message data (repeat as needed)md5.final(); // finalize the computation

// extract the digest value from the object and pretty-print itcdk::str digest; // output string for hash valuedigest.assign(md5.length(),md5.result());printf("the MD5 hash of the message is %s\n", digest.tohex().c_str());

5.2.5 IEEE 32-bit CRC

cdk::CRC crc; // instantiate a CRC objectcrc.add(9, "test data"); // process the message data (repeat as needed)crc.final(); // finalize the computation

// extract the digest value from the object and pretty-print itcdk::str digest; // output string for hash valuedigest = crc.tostring();printf("the 32-bit CRC of the message is %s\n", digest.tohex().c_str());

5.2.6 HMAC

To obtain a 160-bit HMAC-SHA-1 message authentication code, simply call:

cdk::str key = "secret key"; // arbitrary length keycdk::str data = "message data to be MAC’ed";cdk::str hmac = HMAC<SHA>(key,data);

If your system supports templates, you can plug any of the hash functions supportedby this CDK into the HMAC template in place of class SHA in the above code. Other-wise, simply copy (i.e., instantiate) the template code in hmac.h using the desired hashfunction.

NOTE: HMAC-SHA-1 is the only FIPS approved hash-based message authenticationalgorithm. See FIPS 198.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 310: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

304 Cookbook

Information on HMAC (especially on HMAC-MD5) may be found in RFC 2104.Test vectors for both HMAC-MD5 and HMAC-SHA-1 are given in RFC 2202. ForHMAC-SHA-1-96 and its use in IPSEC ESP, see RFC 2404.

For information regarding the operations described on this page see:

• cdk::SHA

• cdk::SHA2

• cdk::MD2

• cdk::MD5

• cdk::CRC

• cdk::HMAC

The next topic is Using the str and num Classes.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 311: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.3 Using the str and num Classes 305

5.3 Using the str and num Classes

This section contains several examples that illustrate how the CDK can be used toperform various data type conversions and other related tasks.

5.3.1 Converting Between cdk::str and cdk::num

The cdk::str and cdk::num classes play a major role in the CDK. cdk::str objects pro-vide both storage and data manipulation functions, including many of the featuresfound in C++’s STL string class, while class cdk::num provides high-precision arith-metic. The two classes have been optimized to work together and conversions betweenobjects of the two types have been made quite simple. That a cdk::str object can simplybe cast into a cdk::num illustrates the close synergy between these classes.

For example, the code listing below creates a PKCS #10 PDU by callingcdk::Key::asn1sign() and that method requires a random cdk::num input (for non-deterministic signature schemes). To obtain this input, it is simplest to apply the con-venient cast to the output of cdk::getrand2():

// generate a new RSA key paircdk::Key k;k.hashtype = hSHA1;k.RSAkeygen(cdk::getrand2(80));

// extract the algorithm ID and public keycdk::str algID = k.asn1parameters(1,0);cdk::str pubkey = k.asn1public();

// create an unsigned PKCS #10 certificate requestcdk::DName dn;dn.cname = "John Doe";cdk::str tbsP10 = makep10raw(dn.toasn1(), algID, pubkey, "");

// sign the PKCS #10 requestcdk::str p10;int i = k.asn1sign(tbsP10, num(cdk::getrand2(80)), p10);// i > 0 indicates an error

Conversely, to convert a cdk::num object into one of type cdk::str, one can simply applythe cdk::num::tostr() method.

5.3.2 Encoding and Decoding Strings

To hex-encode a binary string (with a leading ’0x’ prepended to the output):

cdk::str hexStr = binStr.tohex(1);

To hex-encode a binary string (without a leading ’0x’):

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 312: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

306 Cookbook

cdk::str hexStr = binStr.tohex(0);

To decode (or parse) a hex-encoded string to binary:

cdk::str binStr = cdk::hex("0x0FAC0900AA");

To decode a base64-encoded string to binary

cdk::str b64Str = "D6wJAKo=";cdk::str binStr = b64Str.tobin64();

To base64-encode an octet string according to RFC 1113 and RFC 1421:

b64Str = binStr.tobase64(1);

This method, known as "PEM encoding" or "printable encoding," is the most popularform of encapsulating a base64-encoded octet string and is recommended for mostapplications.

To base64-encode an octet string without the RFC 1113 padding:

b64Str = binStr.tobase64(0);

The next topic is Processing X.509v3 Certificates and CRLs.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 313: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.4 Processing X.509v3 Certificates and CRLs 307

5.4 Processing X.509v3 Certificates and CRLs

This section contains code samples illustrating the use of the cdk::Cert class to processX.509v3 certificates. The following examples are provided:

• Parsing Certificates

– Loading a Certificate

– Obtaining Keys, Algorithm IDs, and Validity Periods

– Processing Certificate Extensions

– Processing Distinguished Names

• Creating A Certificate

• Creating A CRL

• Certificate and CRL Checking

• Issuing an OCSP Status Request

Note:

The certificates and CRLs in all of the examples below are represented as base64-encoded octet strings so that they could be included as string literals in the sourcecode. If you are loading a certificate and/or CRL from a file and are unsure whetherthe data is base64-encoded or not, you should test for the encoding wrapper and,if one is present, remove it before attempting to load the data.To decode a possibly base64-encoded PDU stored in a cdk::str object x, use astatement of the form:if(x[0]!=0x30) x = x.tobin64()

as shown below. (Note that the predicate (x[0]!=0x30) is true when the PDUbegins with the character ’M’ as it does when it is base64-encoded, whereas allbinary ASN.1 encoded PDUs under consideration here start with the tag ’\x30’for an ASN.1 BER- or DER-encoded SEQUENCE.)

5.4.1 Parsing Certificates

To parse an X.509v3 certificate, you must first load it into a cdk::Cert object as illus-trated in the first example below. Subsequent examples show how to process variouscertificate components.

5.4.1.1 Loading a Certificate

In this sample a base64-encoded certificate is decoded and then loaded into a cdk::Certobject.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 314: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

308 Cookbook

// put a sample base64-encoded X.509 certificate into a CDK string objectcdk::str strCertificate =

"MIICJzCCAZCgAwIBAgIBGDANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJVUzEM""MAoGA1UEChMDSVNDMSMwIQYDVQQDExpJU0MgQ0RLIFNhbXBsZSBDZXJ0aWZpY2F0""ZTAeFw0wMzA3MTcwMDAwMDBaFw0wNDA3MTcwMDAwMDBaMEAxCzAJBgNVBAYTAlVT""MQwwCgYDVQQKEwNJU0MxIzAhBgNVBAMTGklTQyBDREsgU2FtcGxlIENlcnRpZmlj""YXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9GQTkukn+153rATR8dh2H""m8ixF7f7Y7bI0VFJnJAQCKqta4/IhFwQIK5F2Gn8j9tITBiXCF7F6XSvaF8bivN1""0zR0pvI11NflEm2kwh7Yw0jZJB17Y3FHg183qYegmm/UwqX5zKUa4xw+cE8XSEqU""uwjg0roBMGhAMzFEihHzLwIDAQABozEwLzAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB""/wQEAwIAYDAPBgNVHQ4ECHJzYS0xMDI0MA0GCSqGSIb3DQEBBQUAA4GBALWGxxo5""5ScpLfECnqEUixFwrzftQGD2ISda7EWp/d7k23fOXgHC7Za18OpvlBUZ3sC2Fg4f""infRHd2J4mXONk5OEdjhJILd58GErcCECg4J2uJPz77/zk+giiXldQEPtG+YOaAb""ZC2SFbdfyYDKiSPhgzdy0/b4cElf4+VzegRM";

// decode the certificate if it’s base64-encodedif (strCertificate[0] != 0x30) strCertificate = strCertificate.tobin64();

// instantiate a Cert object and load the certificate stringcdk::Cert c1;c1.load(strCertificate); // non-zero return value indicates error

5.4.1.2 Obtaining Keys, Algorithm IDs, and Validity Periods

Once a certificate has been loaded into a cdk::Cert object its component parts can beextracted. Here the subject public key, algorithm ID, and validity period dates areaccessed and pretty-printed:

// assume certificate has been loaded into c1 as aboveprintf("Subject public key: %s\n", c1.subject_pub.tohex().c_str());printf("Subject algorithm ID: %s\n", c1.subject_oid.tohex().c_str());printf("notBefore: %f\n", c1.notBefore);printf("notAfter: %f\n", c1.notAfter);

Note:

The main reason to access the subject_oid and subject_pub components of acdk::Cert object is to load them into a cdk::Key object for key wrapping or sig-nature validation (see Processing ASN.1 Encoded Keys).

5.4.1.3 Processing Certificate Extensions

Certificate extensions can be processed serially by calling the getext() method as manytimes as necessary:

// assume certificate has been loaded into c1 as in first example abovefor (int j = 0; ; j++){

cdk::str oid, value;int i = c1.getext(j, oid, value);if ( (i != 0) && (i != CDK_EXTENSION_CRITICAL) )

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 315: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.4 Processing X.509v3 Certificates and CRLs 309

{break; // no more extensions; we’re done

}if (i == CDK_EXTENSION_CRITICAL){

printf("(critical) ");}printf("Extension OID: %s, Value: %s\n", oid.tohex().c_str(), value.tohex().c_str());

}

Note:

ISC can make available additional code for performing ASN.1 encoding and de-coding operations. If you would like this code for processing certificate extensions,please contact us.

5.4.1.4 Processing Distinguished Names

You can use cdk::parsedname() to convert distinguished names into human readable(ASCII) text, as shown here:

// assume certificate has been loaded into c1 as in first example abovecdk::str strSubjectDN, strIssuerDN; // output strings

// convert subject and issuer DNs to ASCII text and print themcdk::parsedname(c1.subject, strSubjectDN, 2); // see function reference for sort order infocdk::parsedname(c1.issuer, strIssuerDN, 2);

printf("SubjectDN: %s\n", strSubjectDN.c_str());printf("IssuerDN: %s\n", strIssuerDN.c_str());

5.4.2 Creating A Certificate

The following code shows how to generate an RSA key pair (see RSA Key Generation)and turn its public key into a self-signed certificate.

// generate a 1024-bit RSA key pair based on a 40-byte random seedcdk::Key k; // instantiate a new Key objectk.RSAkeygen(cdk::getrand2(40), 1024); // non-zero return value indicates error

// build the new tbsCertificate (i.e., the certificate body)cdk::Cert c; // instantiate a new Cert objectc.version = V3; // X.509 version 3c.serial = cdk::num(HASH_SHA(c.subject_pub, 1));

// one way to produce a unique serial numberc.issuer_oid = k.asn1parameters(0,1); // issuer signature algorithm IDc.issuer = c.subject; // issuer DNc.notBefore = time(NULL); // validity periodc.notAfter = time(NULL) + 31536000; // (one year)

cdk::DName dn; // create subject DN

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 316: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

310 Cookbook

dn.cname = "John Doe";dn.org = "XYZ Corp.";dn.country = "US";c.subject = dn.toasn1();

c.subject_oid = k.asn1parameters(1,0); // subject key algorithm ID (RSA)c.subject_pub = k.asn1public(); // subject public keycdk::str body = c.makebody(); // ASN.1 encode the body of the certificate

// sign the tbsCertificate to produce a self-signed certificatecdk::str cert; // output buffer for the certificatecdk::num r; // random seed required for DSA/ECDSA, ignored for RSAif (k.isRSA())

k.SetPadding(cdk::RSA::pkcs1); // specify padding mechanism for RSA, orelse{

PRNG rand; // supply random seed if non-deterministicr = (num) rand.gens(20);

}k.asn1sign(body,r,cert); // sign the certificate; non-zero indicates error

See RFC 3280 for details.

5.4.3 Creating A CRL

Creating a CRL is similar to creating a certificate:

Cert caCert; // assume caCert and caKey have already been initalizedKey caKey;k.hashtype = hSHA1; // specify desired hash function

// build the new tbsCertList (i.e., the CRL body)cdk::CRL c; // instantiate a new CRL objectc.oid = caCert.subject_oid; // one could also use k.asn1parameters(0,1);c.issuer = caCert.subject;c.thisUpdate = cdk::timegmt();c.nextUpdate = cdk::timegmt() + 365.25 * 24 * 60 * 60;

// create list of revoked certificates and reason codes (see below)cdk::str crllist = "";crllist += mkCRLEntry("0x0000001", c.thisUpdate, CRL::certificateHold, CRL::reject);crllist += mkCRLEntry("0x0000002", c.thisUpdate, CRL::cessationOfOperation);crllist += mkCRLEntry("0x0000003", c.thisUpdate);c.list = crllist;

// gather together desired extensions (see below)cdk::str crlexts = "";crlexts += asn1::mkAuthKeyIDExt(caCert); // required for conformance with RFC 3280crlexts += asn1::mkCRLNumberExt(2163);c.extra = crlexts;

cdk::str body = c.makebody(); // put it all together as a tbsCertList

// sign the body to produce the CRL

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 317: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.4 Processing X.509v3 Certificates and CRLs 311

cdk::str crl; // output buffer for the CRLcdk::num r; // random seed required for DSA/ECDSA, ignored for RSAif (k.isRSA())

k.SetPadding(cdk::RSA::pkcs1); // specify padding mechanism for RSA, orelse{

PRNG rand; // supply random seed if non-deterministicr = (num) rand.gens(20);

}k.asn1sign(body,r,crl); // sign the CRL; non-zero indicates error

The following auxiliary function can be used to create the individual entries in thecertificate revocation list (i.e., the items in the sequence of revokedCertificates):

cdk::str mkCRLEntry(const cdk::str &serialno, cdk::TimeT revdate, CRL::Reasons reason,CRL::Instructions instruction)

{str x,y = "";cdk::TimeT t = revdate; // cdkdatetounix(revdate);num serial(hex(serialno));x = asn::integer(serial) + asn::date(t);if ( reason == 6 && instruction > 0 ){

cdk::str strIns = "";switch (instruction){case CRL::callissuer:

strIns = Obj*CRL_hold_callissuer;break;

case CRL::reject:strIns = Obj*CRL_hold_reject;break;

case CRL::pickuptoken:strIns = Obj*CRL_hold_pickuptoken;break;

case none:default:

strIns = Obj*CRL_hold_none;break;

}y = Seq*(Obj*id_ce_holdInstructionCode+Oct*(strIns));

}if ( reason >= 0 ) x += Seq& Seq*(Obj*id_ce_cRLReasons+Oct*(x0A*single(reason))) + y;return Seq*x;

}

while the following functions can be used to create the extensions:

cdk::str mkAuthKeyIDExt(const cdk::Cert &cert){

// compute SHA-1 hash of subject_pubcdk::str subPub = cert.subject_pub;cdk::str hash = HASH(SHA,strSubPub, 1);

cdk::str oid;

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 318: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

312 Cookbook

oid = Obj*id_ce_authorityKeyIdentifier;return Seq*(oid + Oct*(Seq*(x80*hash + xA1*(xA4*(Seq*(cert.subject)))

+ x82*bigend(cert.serial))));}

cdk::str mkCRLNumberExt(int crlNumber){

cdk::str oid = Obj*id_ce_cRLNumber;return Seq*(oid + Oct*(asn::integer(crlNumber)));

}

See RFC 3280 for details.

5.4.4 Certificate and CRL Checking

The following code shows how to check the validity of a certificate pair (i.e., one linkin a certificate path).

cdk::str issuerCert = // the purported issuer certificate"MIICwjCCAiugAwIBAgIBATANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQGEwJVUzEL""MAkGA1UECBMCSUwxETAPBgNVBAcTCE9hayBQYXJrMQwwCgYDVQQKEwNJU0MxEDAO""BgNVBAsTB0RlbW8gQ0ExHDAaBgNVBAMTE0NlcnRpZmljYXRlIE1hbmFnZXIwHhcN""MDMwNjI0MDUwMDAwWhcNMDUwNjI0MDUwMDAwWjBrMQswCQYDVQQGEwJVUzELMAkG""A1UECBMCSUwxETAPBgNVBAcTCE9hayBQYXJrMQwwCgYDVQQKEwNJU0MxEDAOBgNV""BAsTB0RlbW8gQ0ExHDAaBgNVBAMTE0NlcnRpZmljYXRlIE1hbmFnZXIwgZ8wDQYJ""KoZIhvcNAQEBBQADgY0AMIGJAoGBAMPYg8Up8s3CAJICbNyW/CTxbj4yzaA8ZbcX""2t969MysICe0EI2/Z2xuTXuhY6hjFi6B9d/+yVLB17zHqpEpSbafCQMZvGc1pe7u""bcf+4wFtt5yRo7WRz6y/bMUnpCB+TlT++w8ZKTLwXNNLgAAIRC8WtawKx/c7aCJo""lekN65VXAgMBAAGjdjB0MBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTAD""AQH/MB0GA1UdDgQWBBSUr9rVPeS8n/o4spfRv3Kp+4PGCTAfBgNVHSMEGDAWgBSU""r9rVPeS8n/o4spfRv3Kp+4PGCTAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQEF""BQADgYEAnsGoKxDrTn+BGZNxUTjbVwv6Lkk9xr2R2y68JiUY48fGgu5IzO9QSsl7""UmqLAZCryOY08lNxduVXyiwRHSt8088v+6qvCgAjhxTZIn8EFOECom6tKTV9Hp6h""dU+z5aFhfSgJRKL0SzTrBg8P2/LIqMMotKBoQWqjnB+aP2d4jgk=";

cdk::str subjectCert = // the subject certificate"MIID2DCCA0GgAwIBAgIBFzANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQGEwJVUzEL""MAkGA1UECBMCSUwxETAPBgNVBAcTCE9hayBQYXJrMQwwCgYDVQQKEwNJU0MxEDAO""BgNVBAsTB0RlbW8gQ0ExHDAaBgNVBAMTE0NlcnRpZmljYXRlIE1hbmFnZXIwHhcN""MDMwNjI3MTk0ODU3WhcNMDQwNjI2MTk0ODU3WjBJMREwDwYDVQQMEwhNaXggQ2Fz""ZTEOMAwGA1UEAxMFVGVTVDMxJDAiBgkqhkiG9w0BCQEWFXRlc3QzQGluZm9zZWNj""b3JwLmNvbTCCAbYwggErBgcqhkjOOAQBMIIBHgKBgQCT6JZdr9nf7P0AtGa2j5Dq""aK9dyf7ZFSeNGzoTdHHmVZbDf+0MeCn/j4Mx+BonAEOOzcwJRH3Dl8aF85cpT3Ir""zEhK7fKL7SWqqzXTWmXbH9YsnXulWET+sflAHmcTQJM+5DxU5NxFlADXrWEki4Oi""Ykg1sx//LZWVpbkLJ25E+QIVALtd/kLeEVwA217xsDiDRNbBVIWtAoGAaSefjrq4""Do8k8BhGIZZjbEwiVGTwEz4PLyHnu+0dhT8G65SahoUKMKm1ss6oMOqtAOe99h68""gcxB3rr/G1v9nyqksRMpsTw9xpURJ/vIa001M4I7+XpY3i/x+cmzF3ujSU7V4AA4""Pb1qaZ1XiVSPzvUHNo5L5m7rDwh1c4y8/MUDgYQAAoGAAJevjq95fOwS9l3Cr1xq""KIftJsWoT16u37VhiRfGEq+/JEkDjBkC22S10E7Iyv7p75Lv617N+2pOYQRWtcxp""U169I60gxNvW6c2eLXHA+d9vKvaIqjmsYP9K/poqMJ2sdK50OQJxId4xOWiN9KLp""BicXOLjcp1VHE1MaNST1fQWjgZUwgZIwEQYJYIZIAYb4QgEBBAQDAgWgMA4GA1Ud""DwEB/wQEAwIF4DAYBgNVHREEETAPgQ1hbGljZUBpc2MuY29tMB8GA1UdIwQYMBaA""FJSv2tU95Lyf+jiyl9G/cqn7g8YJMDIGA1UdCQQrMCkwEgYJYIZIAWUCAgFEMQUW""A0FCQzATBgpghkgBhvhCAwEEMQUWA1ImRDANBgkqhkiG9w0BAQUFAAOBgQCq778P"

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 319: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.4 Processing X.509v3 Certificates and CRLs 313

"0yNeutqWu7pomHJ8yWZ7ZC2w8njvOLLJoECaaP5j9xt6hRdyCqIfzx3hVWxv1VOb""dHgEfNViMFPaURYRJWbfX0Gn7+DJ9Lluby6prXPm0rTIZ4GdRCBA58dhn7ct5itc""YorKfy79SaeumDvsjIvbe7iR6WO5rDxuVChaBA==";

// decode the certificates if they are base64-encodedif (issuerCert[0] != 0x30) issuerCert = issuerCert.tobin64();if (subjectCert[0] != 0x30) subjectCert = subjectCert.tobin64();

// check the signature in subjectCert using public key in issuerCertint i = cdk::checkcert(issuerCert, subjectCert);// checkcert() returns 0 if certificate is valid, non-zero otherwiseprintf("Certificate is %s\n", i ? "INVALID!" : "valid");

The following code shows how to test a certificate against a CRL.

cdk::str strCertificate = // a base64-encoded certificate"MIIChjCCAe+gAwIBAgIBNjANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQGEwJVUzEY""MBYGA1UEChMPVS5TLiBHb3Zlcm5tZW50MQwwCgYDVQQLEwNEb2QxEDAOBgNVBAsT""B1Rlc3RpbmcxFTATBgNVBAMTDENBMS1JQy4wNC4wMTAeFw05ODAxMDExMjAxMDBa""Fw00ODAxMDExMjAxMDBaMGAxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9VLlMuIEdv""dmVybm1lbnQxDDAKBgNVBAsTA0RvRDEQMA4GA1UECxMHVGVzdGluZzEXMBUGA1UE""AxMOVXNlcjEtSUMuMDQuMDEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM2d""GkraKGdIi6EXxAu6/ekMqDloX5YSVBGh4Hp2faujr1u4j8Lp8afqjngRxFUpTqGb""qH0ETgm4cVPXmc9rUvUzYTMdxTUmIZ+iW+ULZEvzNB712kxRPCD2kDFN2fH2ai8m""iXr434w+weLm8VQN4jJGo4nswhSs2w1gsUmWyn/ZAgMBAAGjUjBQMA4GA1UdDwEB""/wQEAwIF4DAWBgNVHSAEDzANMAsGCWCGSAFlAwEwATARBgNVHQ4ECgQITsLx/sO1""edwwEwYDVR0jBAwwCoAIbMuZ73onuZswDQYJKoZIhvcNAQEFBQADgYEAeKft0RM8""/b3zQodaKrTdWiFyLg5fzoOsTecSfdFPXoqz9J5ejLVkvJevSmfXJrIUhKXySzsQ""i+GazuTh/hvWjwUTIvmupi+EiFudnMpXCro8bgi48+NkepNjXvjsSmOfzlrK3Sxt""pH5dqonL6LHjGyg+Xp0Nor1m5g1rLHyrcEk=";

cdk::str strCRL = // a base64-encoded CRL"MIIBSzCBtQIBATANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQGEwJVUzEYMBYGA1UE""ChMPVS5TLiBHb3Zlcm5tZW50MQwwCgYDVQQLEwNEb2QxEDAOBgNVBAsTB1Rlc3Rp""bmcxFTATBgNVBAMTDENBMS1JQy4wNC4wMRcNOTkwMTAxMTIwMTAwWhcNNDgwMTAx""MTIwMTAwWqAjMCEwCgYDVR0UBAMCAQEwEwYDVR0jBAwwCoAIbMuZ73onuZswDQYJ""KoZIhvcNAQEFBQADgYEAMk6DRztz1AyFnFr1KAlbjLLwxtQplf2eIc//zUkDFVUH""tX5TrEC/ijUaItjdkOoPGQfpnL0w8xwyqWndMh593QPCqIJTtv/iACoiJNZ90ZJS""0adcdZ+AEmQpa0Zv0e1JOqRrPoAfTq4HrOfRvhBwhvKQNtTExupW/EBudznKC6Q=";

// decode the certificate or CRL if either is base64-encodedif (strCertificate[0] != 0x30) strCertificate = strCertificate.tobin64();if (strCRL[0] != 0x30) strCRL = strCRL.tobin64();

cdk::CRL crl; // instantiate a CRL object and load thecrl.load(strCRL); // ASN.1 encoded CRL (test return code for error)

// check to see if the certificate has been revokedcdk::Cert::Time tDate; // output buffer for revocation date (if any)int nReason; // reason for revocation (if any)int i = crl.isRevoked(strCertificate, tDate, nReason);if (i)

printf("Certificate has been revoked: reason code = %d\n", nReason);else

printf("Certificate does not appear on this CRL\n");

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 320: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

314 Cookbook

5.4.5 Issuing an OCSP Status Request

The following function illustrates how to implement a simple OCSP client:

int OCSP_CheckCert(const str &caCert, const str &subCert, const str &svrURL,const str &svrCert)

{/* issue an OCSP status request

parameters:caCert issuer certificatesubCert subject certificate whose validity is to be testedsvrURL URL of OCSP respondersvrCert responder certificate (for authentication of response)

returns:0 if certificate is valid1 if certificate has been revoked2 if certificate status is unknown (responder not authoritative for this CA)3 protocol error4 signature on response is invalid (reponse cannot be trusted)

*/// build the OCSP requestcdk::str nonce = cdk::getrand2(16);cdk::str req = cdk::make_ocsp_req(caCert, subCert, nonce);

// query the serverCAmHttpSocket http;http.m_lpszContentType = "Content-Type: application/ocsp-request \r\n";std::string sResponse = http.GetPage(svrURL.c_str(), true, req.c_str(), req.length());cdk::str res = str_(sResponse);

// check the response (and its signature)cdk::asn sinfo, certs, dn;cdk::TimeT revtime;int i = check_ocsp(req, res, sinfo, revtime, certs, dn);if ( (i == 0) || (i == 1) ) // if OK or revoked, check responder’s signature{if ( check_signinfo(svrCert, sinfo) != 0 )i = 4; //signature is invalid!

}return i;

}

OCSP is specified in RFC 2560. The CAmHttpSocket class used here for the HTTPPOST operation is available from the Code Project.

The next topic is Handling Public and Private Keys.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 321: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 315

5.5 Handling Public and Private Keys

This section contains examples showing how to manage public and private keys usingthe cdk::Key class. Samples are provided for the following procedures:

• Processing ASN.1 Encoded Keys

– Parsing X.509 Certificates

– Parsing PKCS #12 PDUs

– Loading ASN.1 Encoded Keys

• Processing Raw Key Components

– RSA

– DSA

– ECDSA

• Generating Public and Private Keys

– RSA Key Generation

– DSA/DH Key Generation

– ECDSA/ECDH Key Generation

• Processing Digital Signatures

– Signing

– Validating

• Handling Symmetric Keys

– Wrapping With a Public Key

– Unwrapping With a Private Key

• Diffie-Hellman Key Agreement

These days public keys are typically presented as ASN.1 encoded X.509 certificates(see RFC 3280) or, with additional information, in password protected PKCS #12files or "protocol data units" (PDUs) (see RFC 2437). PKCS #8 PDUs are also usedfor the storage and transport of private keys.

The first step in using such key formats with CDK functions is to load the certificate orPKCS #8/12 PDU into an object of the appropriate CDK class (cdk::Cert or cdk::Key).Once the PDU is parsed, its components can be accessed separately or used in a widevariety of public and private key operations. The code fragments below illustrate sev-eral of the most popular operations.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 322: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

316 Cookbook

Note:

The certificates and CRLs in all of the examples below are represented as base64-encoded octet strings so that they could be included as string literals in the sourcecode. If you are loading a certificate and/or CRL from a file and are unsure whetherthe data is base64-encoded or not, you should test for the encoding wrapper and,if one is present, remove it before attempting to load the data.To decode a possibly base64-encoded PDU stored in a cdk::str object x, use astatement of the form:if(x[0]!=0x30) x = x.tobin64()

as shown below. (Note that the predicate (x[0]!=0x30) is true when the PDUbegins with the character ’M’ as it does when it is base64-encoded, whereas allbinary ASN.1 encoded PDUs under consideration here start with the tag ’\x30’for an ASN.1 BER- or DER-encoded SEQUENCE.)Similarly, all raw key components in the code fragments below are represented asstrings of hex digits (in ASCII). They must be converted back into binary formbefore being loaded into a Key object. The function used for this purpose iscdk::hex().

5.5.1 Processing ASN.1 Encoded Keys

5.5.1.1 Parsing X.509 Certificates

If you have an ASN.1 encoded certificate and wish to obtain the subject public key andalgorithm identifier (the key type, possibly with specified parameters) from it, you mayfollow this example:

cdk::str strCertificate = // a sample base64-encoded certificate"MIICJzCCAZCgAwIBAgIBGDANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJVUzEM""MAoGA1UEChMDSVNDMSMwIQYDVQQDExpJU0MgQ0RLIFNhbXBsZSBDZXJ0aWZpY2F0""ZTAeFw0wMzA3MTcwMDAwMDBaFw0wNDA3MTcwMDAwMDBaMEAxCzAJBgNVBAYTAlVT""MQwwCgYDVQQKEwNJU0MxIzAhBgNVBAMTGklTQyBDREsgU2FtcGxlIENlcnRpZmlj""YXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9GQTkukn+153rATR8dh2H""m8ixF7f7Y7bI0VFJnJAQCKqta4/IhFwQIK5F2Gn8j9tITBiXCF7F6XSvaF8bivN1""0zR0pvI11NflEm2kwh7Yw0jZJB17Y3FHg183qYegmm/UwqX5zKUa4xw+cE8XSEqU""uwjg0roBMGhAMzFEihHzLwIDAQABozEwLzAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB""/wQEAwIAYDAPBgNVHQ4ECHJzYS0xMDI0MA0GCSqGSIb3DQEBBQUAA4GBALWGxxo5""5ScpLfECnqEUixFwrzftQGD2ISda7EWp/d7k23fOXgHC7Za18OpvlBUZ3sC2Fg4f""infRHd2J4mXONk5OEdjhJILd58GErcCECg4J2uJPz77/zk+giiXldQEPtG+YOaAb""ZC2SFbdfyYDKiSPhgzdy0/b4cElf4+VzegRM";

// decode the certificate if it is base64-encoded (this one is!)if (strCertificate[0] != 0x30) strCertificate = strCertificate.tobin64();

// load binary ASN.1 encoded certificate data into a Cert objectcdk::Cert c1;c1.load(strCertificate); // nonzero return value indicates parsing error

// now individual certificate components may be accessedcdk::str strPub, strAlgID; // output buffers for:

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 323: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 317

strPub = c1.subject_pub; // subjectPublicKey andstrAlgID = c1.subject_oid; // subject AlgorithmIdentifier

5.5.1.2 Parsing PKCS #12 PDUs

To obtain the leaf certificate and private key from a PKCS #12 PDU, you simply pro-vide the owner’s password and call parsep12() as illustrated in this example:

cdk::str strP12 = // a sample base64-encoded PKCS #12 PDU"MIIGQgIBAzCCBggGCSqGSIb3DQEHAaCCBfkEggX1MIIF8TCCAt8GCSqGSIb3DQEH""BqCCAtAwggLMAgEAMIICxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIPtPP""DiTkLIQCAgQAgIICmCAJ/jf5UOduGWpozCah9dLjcJdG5xb3FlHBaN1c35VDOGK3""1BZUQDvGsYttBASLD+wXY3i/MnEAwOX6c4EfL17JQtIJfE7mCAukaqUbJtLtQsvJ""7JMMwfUhRkEWQA60rJV2/CaL2bewy1MIFrduf02ImTNbB20059/ewn8Ya7cXZlrH""bjWhv0OjeYWvBstBRCZkz2w0Yyu9F8KGVS0HHDuiBUMU0gMBnp7COUumzZ9hzYGi""GNz0VivzX86cL/wiNvSyTpbZFsOw0+NxLdG1NlSbwbFu2Ay9uQI9xh886odnsLsn""u9fTpkFFlBTEwyawP8UUEjMNiXo+SVX93xGi7wfoe9HmpXBsvQ4suPzqs8j8SJ8b""9pOKF40eb48GxSYUbPJ6kfBan45Doe7ypkApTpejAebVLz00u5yH+A3HiJm+Okk2""Hzq+/Rh/vcY2+jjimZfV0qVVPLyDKTSWLgo7D9L4dCeeWU3VCdAbeyUKnx2V8Av9""qU0q8qeDLGaXGyxZ24G7UQzaaUIIOn0wUFSjupGFctMPXz3/QvkUQgSuLKRhMWnk""e6UNA2N0y5gMMmcfNh6n226m6t7lCce3KXRcCAZr0IJMpdldO7tft0v2dqo6reuE""x3bv5I3ink0SJSz0xZr92p9dcqcO067PIZ3TjQaLyziYJUPvyo53Z7udPB8qTUYn""v9U+3Ovjh2eGQ/5KvFathlAPav+Styn4w5LIKPDiyxXfrADeELEYOgV9AauDVaiC""vrWESXbgTbCaMcYTrWDH4tWlhXLtBbTSlemAVClUa1BvSGRvAEJiF+46S1oESwQx""ZTw0uBtmiuVtccRrzhS4YvxAgsBUqstd3B45RCdi8v0uECAzEYBkfdiW7ZlfxQKa""q2s4oC0wggMKBgkqhkiG9w0BBwGgggL7BIIC9zCCAvMwggLvBgsqhkiG9w0BDAoB""AqCCAqYwggKiMBwGCiqGSIb3DQEMAQMwDgQIL5knnoi6f/8CAgQABIICgCHYGIzu""7kzK8eynvtCUzMxyrJ/k/BHnEDJ70TADRxfgn/8GylDGvxblJZaaa+W5XF0pIf7/""C7ZbBRzoqzhkK2IbH1jKGtFOfP81kxpw9pLW2A01AT0rT62uEDleP1EbPKFgehBm""FPp/F0y06UbewfluW6nqky5feqmTQJWBWv8ctRsH2JeOxoI4MkEPOoOYUeViPM3w""YIzon6GxiNiUP+7l4Eh+WhM2ViKGRr/m02wWvgL9mnkj/aOqvPN+o7i6Up6+oVRz""sWfUyQip5V3n+J7y1an+lS3nZDjxCXy0f4O9DyNV/96KMrQDFCbzRVBQNqttChuK""yqsai+HQH5+xywiwCSQEfMnVElZUB2O+nCZ8Dd3PbXuZ0bl3getc7YfgOhAI8+hX""HXKDzwmGl9VYwctAzqd/LLVG+sg4zJBkideLB8fW9ciE4LOsa6QeVGNSLwn61lGJ""AMxIiIK19xFmnvqyeBhF1fWmPJhcnkUaWNfbmSco+u/156B5vKu6cBO4i/+/oG3M""lOAyMV+jPB1YGOo8p1K5PiC0LODHKpbinK+SM3NYx1RbxEn+8rNQcOURvE0cchxs""C/dqV00w/9lfA797mElW5ToOYFJot3G5NWRxJ6tf1myrMJ7VUSsJFN1aOUPj+AL5""U5Dgh715z5ji+ExHLolJabsCkTd76137NoNPR8/MvWhRY94qdJABU55kyjjJPlJU""wN0kE/At+wjSCXkI589qnuSJHr37X3UtUbTeK/r0QiL6ennxIkwUDqsiHR/ZAEy1""Wdwjh9ij4Y9ogYB7aePtlZSqfO5FGHbgGs8EvOmFwotXM5mYCaXHMZE4We7KBto8""Clcx/7TxvVH0OgUxNjAPBgkqhkiG9w0BCRQxAh4AMCMGCSqGSIb3DQEJFTEWBBQw""MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMCEwCQYFKw4DAhoFAAQUf8HYKKKVoyHkyeOX""hpvt5t+Kn4IECCYQiCMLyK+cAgIEAA==";

// decode the PDU if it is base64-encoded (this one is!)if (strP12[0] != 0x30) strP12 = strP12.tobin64();

// parse the PDUcdk::Chain chn; // buffer for PDU’s certificate chaincdk::str p12oid, strPrv; // buffers for algID and private keycdk::str crl; // buffer for any CRLscdk::parsep12(strP12, "password", chn, p12oid, strPrv, crl);

// a nonzero return value indicates a parsing error

// find end-user’s certificate in the chain

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 324: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

318 Cookbook

int nEndUserCert = chn.find(Chain::user);if (nEndUserCert == -1) nEndUserCert = 0; // leaf certificate not found

// and load it into a new Cert objectcdk::Cert c1;c1.load(chn.index(nEndUserCert));

// now we can access individual certificate componentscdk::str strPub, strAlgID; // output buffers for:strPub = c1.subject_pub; // subjectPublicKey andstrAlgID = c1.subject_oid; // subject AlgorithmIdentifier

5.5.1.3 Loading ASN.1 Encoded Keys

Once you have obtained a subject’s algorithm identifier and key(s) you can load theminto a cdk::Key object to perform cryptographic operations (see Wrapping With a Pub-lic Key, Unwrapping With a Private Key, Signing, and Validating).

For encryption and signature validation, only the public key is required:

// load an ASN.1 encoded public key into a new Key objectcdk::Key key;key.loadoid(strAlgID); // a nonzero return value indicates an errorkey.loadpub(strPub); // a nonzero return value indicates an error

For decryption and signing, you’ll need the entire key pair:

// load an ASN.1 encoded key pair into a new Key objectcdk::Key key;key.loadoid(strAlgID); // a nonzero return value indicates an errorkey.loadprv(strPrv); // a nonzero return value indicates an errorkey.loadpub(strPub); // a nonzero return value indicates an error

Note:

Loading a private key clears the Key’s public components, so you must alwaysload a private key before loading its corresponding public key. Alternately, youload the private key and have the CDK recompute the public components.

To load a private key into a Key object and recompute the Key’s public components:

// load an ASN.1 encoded private key and recompute the public keycdk::Key key;key.loadoid(strAlgID); // a nonzero return value indicates an errorkey.loadprv(strPrv); // a nonzero return value indicates an errorkey.genpub(); // a nonzero return value indicates an error

To obtain ASN.1 encoded key information from an existing Key object:

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 325: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 319

cdk::Key key; // assume this contains a complete key paircdk::str strAlgID, strPub, strPrv; // output buffers for requested componentsstrAlgID = key.asn1parameters(1,0); // get the key’s algorithm identifierstrPub = key.asn1public(); // get the public keystrPrv = key.asn1private(); // get the (unprotected) private key

5.5.2 Processing Raw Key Components

In the event that your key components are not ASN.1 encoded you can still use themwith the CDK. The following examples illustrate the handling of so-called ’raw’ RSA,DSA, and ECDSA key components.

5.5.2.1 RSA

In the samples below we refer to the public modulus and exponent as the public keycomponents (usually denoted n and e), while the two prime factors of the modulus (pand q) comprise the private key.

To load raw RSA public key components into a Key object:

cdk::str strRSAPUB = hex( // a sample public modulus"D025F3A723231FA23CE4CE011A595787A06707AEA61443E15FAEDD6D59634E44""BA5CE36695C4D441160F3A2FB9CC757542F60804E94A58B610722EBFDE3DBF08""3F6FDD88AE6F282BF215542C929AF95F0A8FD44CC669A6CB72C9B920305E3B4D""13AEADE6A53CAC1BD9E9BC4037A6D4F18E6B94430DBEABF1697121418A2A6AC7");

// load the binary modulus with the popular public exponent 65537 (F4)cdk::Key key;key.RSALoadPublic(num(65537), num(strRSAPUB));

// a nonzero return value indicates an error

To load raw RSA key pair components into a Key object, load the private componentsfollowed by the public ones, then call initialize() to compute the intermediate internalprivate key components (such as Chinese Remainder Theorem coefficients):

cdk::str strRSAP = hex( // a prime"D0A1379B3EBFA301DC59196F18593C45E519287A23297589109F4B3C50D7B0DF""729D299BC6F8E9EF9066971FB444AC06613FC8D63795BE9AD0BEAF5501193B31");

cdk::str strRSAQ = hex( // another prime"FF68BF231FF2B3704AEDE04EECB51E50CA698EFD50A1379B3EBFA301DC59196F""18593C45E519287A23297589109F4B3C50D7B0DF729D299BC6F8E9EF90669777");

cdk::str strRSAPUB = hex( // the product"D025F3A723231FA23CE4CE011A595787A06707AEA61443E15FAEDD6D59634E44""BA5CE36695C4D441160F3A2FB9CC757542F60804E94A58B610722EBFDE3DBF08""3F6FDD88AE6F282BF215542C929AF95F0A8FD44CC669A6CB72C9B920305E3B4D""13AEADE6A53CAC1BD9E9BC4037A6D4F18E6B94430DBEABF1697121418A2A6AC7");

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 326: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

320 Cookbook

// load the prime factors of the modulus as the private keycdk::Key key;key.rsai.loadpriv(num(strRSAP), num(strRSAQ));

// a nonzero return value indicates an error// load the modulus with the exponent 65537 (F4) as the public keykey.RSALoadPublic(num(65537), num(strRSAPUB));

// a nonzero return value indicates an error

key.rsai.initialize(); // computes internal RSA private key values

To load raw RSA private key components and reconstruct the corresponding public keycomponents:

cdk::str strRSAP = hex( // a prime"D0A1379B3EBFA301DC59196F18593C45E519287A23297589109F4B3C50D7B0DF""729D299BC6F8E9EF9066971FB444AC06613FC8D63795BE9AD0BEAF5501193B31"

);cdk::str strRSAQ = hex( // another prime

"FF68BF231FF2B3704AEDE04EECB51E50CA698EFD50A1379B3EBFA301DC59196F""18593C45E519287A23297589109F4B3C50D7B0DF729D299BC6F8E9EF90669777"

);

// load the prime factors of the modulus as the private keycdk::Key key;key.rsai.loadpriv(num(strRSAP), num(strRSAQ));

// a nonzero return value indicates an error// specify a public exponent and recompute internal RSA private key valueskey.rsai.expo = num(65537); // 65537 is a popular choicekey.rsai.initialize(); // a nonzero return value indicates an error

// now regenerate the public componentskey.rsai.genpub(); // a nonzero return value indicates an error

To obtain raw key components from a Key object containing a complete RSA key pair:

cdk::Key key; // assume that this contains a complete key pairnum p, q, pq, expo // ouput buffers for key componentskey.RSAGetRawPublic(expo, pq); // access the public exponent and modulusp = key.rsai.p; // access the first prime factorq = key.rsai.q; // access the second prime factor

5.5.2.2 DSA

Loading raw key components is somewhat more complicated for DSA than it is forRSA because you must explicitly provide the DSA group parameters. The CDK comeswith a number of predefined DSA parameter sets in parms.c and using one of themis easiest if you are generating and using keys for a standalone application. You may,however, use the CDK to generate your own parameters or import existing parametersets from another source as an ASN.1 encoded algorithm identifier.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 327: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 321

The code fragments in this section illustrate how to generate a new DSA parameter set(using the CDK’s DSA_GenerateParameters() function) and then ASN.1 encode it. Ifyou already have a set of raw DSA parameters, you can follow this example to obtainan ASN.1 encoded representation – just skip the parameter generation step:

// generate a new 1024-bit DSA parameter setint nNP = 1024; // requested size of p in bits; denoted by L in FIPS 186-2int H = 2; // base for g (default value is NIST’s 2; ISC uses 7)cdk::num p, q, g; // output buffers for DSA parametersint start = 0; // starting value of counterint counter = 0; // output buffer for final iteration countcdk::str seed = cdk::getrand2(20); // initial random 20-byte seed valuePRNG pi; // SHA-1 based PRNG to use if we need more seed values

// retry until we find a suitable seedwhile (

DSA_GenerateParameters(seed,160,nNP,q,p,g,counter,start,H) == CDK_INVALID_SEED)

strSeed = pi.gens(20);

// obtain hexadecimal representations of p,q,gcdk::str strQ = q.tostr().tohex(1);cdk::str strP = p.tostr().tohex(1);cdk::str strG = g.tostr().tohex(1);

// populate a GroupData object with these parameterscdk::GroupData cd;cd.deg = 1; // flag for SHA-1 (for ECDSA, degree of field extension)cd.seed = ""; // seed is not encoded with parameterscd.order = strQ.c_str(); // qcd.p = strP.c_str(); // pcd.a = 0; // only for ECDSA (1st polynomial coefficient)cd.b = 0; // only for ECDSA (2nd polynomial coefficient)cd.Gx = strG.c_str(); // g (for ECDSA, x coordinate of EC base point)cd.Gy = 0; // only for ECDSA (y coordinate of base point)cd.start = 0;cd.genseed = H;

// get an ASN.1 encoded algorithm ID for these parameterscdk::str strAlgID = cd.oid();

If you want to use one of the predefined DSA parameter sets provided by ISC inparms.c, you can quickly get its algorithm ID without explicitly constructing a Group-Data object. For example, the ASN.1 encoded algorithm ID for ISC’s 1024-bit DSAparameters can be obtained as follows:

cdk::str strAlgID = DSA_Parms[ISCDSA1024].oid();

Once you have the ASN.1 encoded algorithm ID for a DSA key, you can load its rawpublic key component like this:

cdk::str strDLPUB = hex( // a sample public key

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 328: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

322 Cookbook

"19131871D75B1612A819F29D78D1B0D7346F7AA77BB62A859BFD6C5675DA9D21""2D3A36EF1672EF660B8C7C255CC0EC74858FBA33F44C06699630A76B030EE333"

);

cdk::Key key;key.loadoid(DSA_Parms[FIPSEXAMPLE].oid()); // load algorithm IDkey.DLLoadPublic(num(strDLPUB)); // load public key value

To load raw DSA public and private key components:

cdk::str strDLPRV = hex("2070b3223dba372fde1c0ffc7b2e3b498b260614");cdk::str strDLPUB = hex(

"19131871D75B1612A819F29D78D1B0D7346F7AA77BB62A859BFD6C5675DA9D21""2D3A36EF1672EF660B8C7C255CC0EC74858FBA33F44C06699630A76B030EE333"

);

cdk::Key key;key.loadoid(DSA_Parms[FIPSEXAMPLE].oid()); // load algorithm IDkey.loadprivate(num(strDLPRV)); // load private key valuekey.DLLoadPublic(num(strDLPUB)); // load public key value

To load raw DSA private key components and generate the corresponding public key:

cdk::str strDLPRV = hex("2070b3223dba372fde1c0ffc7b2e3b498b260614");cdk::str strDLPUB = hex(

"19131871D75B1612A819F29D78D1B0D7346F7AA77BB62A859BFD6C5675DA9D21""2D3A36EF1672EF660B8C7C255CC0EC74858FBA33F44C06699630A76B030EE333"

);

cdk::Key key;key.loadoid(DSA_Parms[FIPSEXAMPLE].oid()); // load algorithm IDkey.loadprivate(num(strDLPRV)); // load private key valuekey.genpub();

To extract raw key components from a Key object containing a complete DSA orECDSA key pair:

cdk::Key key; // assume this contains a (EC)DSA key pairnum priv, pub, y; // output buffers for raw components

// get an ASN.1 encoded algorithm ID containing the (EC)DSA parameterscdk::str strAlgID = key.asn1parameters(1,0);key.GetRawPrivate(priv); // get raw private keykey.DLGetRawPublic(pub, y); // y is only used for ECDSA; ignore for DSA

5.5.2.3 ECDSA

As it was for DSA, loading raw keys is more complicated for ECDSA than for RSAbecause you must explicitly provide an ECDSA parameter set specifying the ellipticcurve. The CDK comes with a number of predefined ECDSA parameters in parms.c,

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 329: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 323

including all of the prime and binary curves published by NIST in FIPS 186-2, andthese are easiest to use if you are generating and using ECDSA keys in an applicationthat only needs to interoperate with other applications that use these same curves.

Note:

The CDK does not support binary elliptic curve operations that use an optimalnormal basis representation for the underlying field elements, so parameter setsfor those NIST examples that use ONB representations are omitted.

If you want to generate your own ECDSA parameters or have parameters from anothersource, you must obtain an appropriate ASN.1 encoded algorithm identifier and use itto initialize your Key objects. ANS.1 encoded algorithm identifiers may be created byfilling out a cdk::GroupData object and calling its oid() method.

The following code fragment shows how to create an algorithm identifier specifyingthe elliptic curve labeled ’P-192’ by NIST:

// create an ASN.1 encoded algorithm ID for NIST Curve P-192cdk::GroupData cd;cd.deg = 0;cd.a = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC";cd.seed = "0x3045AE6FC8422F64ED579528D38120EAE12196D5";cd.order = "0xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831";cd.p = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF";cd.b = "0x64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1";cd.Gx = "0x188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012";cd.Gy = "0x7192B95FFC8DA78631011ED6B24CDD573F977A11E794811";cd.start = 0;cd.genseed = 0;cdk::str strECDSAP192 = cd.oid();

The following code fragment shows how to create an algorithm identifier specifyingthe Koblitz curve labeled ’K-163’ by NIST:

// create an ASN.1 encoded algorithm ID for NIST Curve K-163cdk::GroupData cd;cd.deg = 163;cd.a = "0x1";cd.seed = "";cd.order = "0x04000000000000000000020108a2e0cc0d99f8a5ef";cd.p = "0x0800000000000000000000000000000000000000c9";cd.b = "0x1";cd.Gx = "0x02fe13c0537bbc11acaa07d793de4e6d5e5c94eee8";cd.Gy = "0x0289070fb05d38ff58321f2e800536d538ccdaa3d9";cd.start = 0;cd.genseed = 0;cdk::str strECDSAK163 = cd.oid();

Of course, since the CDK provides predefined parameter sets for these two curves, itisn’t necessary to explicitly construct the algorithm IDs yourself! You can simply use

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 330: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

324 Cookbook

the oid() method after picking out the appropriate element of the NIST_Curves[] array.Here are two examples:

strECDSAP192 = NIST_Curves[NISTP192].oid();

strECDSAK163 = NIST_Curves[NISTK163].oid();

Once you have an ASN.1 encoded algorithm identifier for your key type you can loadraw ECDSA private key components into a Key object and then generate the corre-sponding public key components as follows:

cdk::str strECPRV = cdk::hex("AA8A7935B06BC5CA9749BBA4053A999667C0FDA287B759E1");cdk::Key k9;k9.loadoid(NIST_Curves[0].oid());

// a nonzero return value indicates an errork9.loadprivate(num(strECPRV));k9.genpub(); // a nonzero return value indicates an error

Note:

No direct mechanism is provided for loading a raw ECDSA public key into theCDK. The recommended approach to loading an ECDSA public key is to ASN.1encode the raw key and call the load method for ASN.1 encoded keys. If you havea need to load raw keys directly, contact ISC and appropriate code can be provided.

5.5.3 Generating Public and Private Keys

The simple examples in this section illustrate the creation of new RSA, DSA, andECDSA key pairs.

5.5.3.1 RSA Key Generation

To generate a new RSA key pair, you must specify a seed value for the prime numbersearch required to find the private factors of the modulus. You may also optionallyoverride the default key size of 1024 bits, specify a public exponent other than 65537,and request more than two prime factors.

// generate a 1024-bit RSA key with 2 primes and a public exponent of 65537cdk::Key key;key.RSAkeygen(cdk::getrand2(80)); // a nonzero return value indicates an error

5.5.3.2 DSA/DH Key Generation

For DSA keys, you must supply a random seed value and specify an algorithm identifier(containing specifications for the group parameters). As shown here, it is simplest touse one of the predefined parameter sets in DSA_Parms[], letting the oid() methodprovide its ASN.1 encoded algorithm identifier.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 331: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 325

cdk::Key key;key.DLkeygen(cdk::getrand2(80), DSA_Parms[ISCDSA1024].oid());

// a nonzero return value indicates an error

5.5.3.3 ECDSA/ECDH Key Generation

For ECDSA keys, you must specify an algorithm identifier (containing specificationsfor the elliptic curve parameters). As shown here, it is simplest to use one of theNIST_Curves, letting its oid() method provide the required ASN.1 encoded algorithmidentifier.

cdk::Key key;key.DLkeygen(cdk::getrand2(80), NIST_Curves[NISTP384].oid());

// a nonzero return value indicates an error

5.5.4 Processing Digital Signatures

5.5.4.1 Signing

Given a Key object containing a private key, you can obtain a digital signature over amessage digest in the following manner:

cdk::Key key; // contains signer’s private keycdk::Signature sig; // output buffer for signature

// sample SHA-1 digest to be signedcdk::str digest = hex("A9993E364706816ABA3E25717850C26C9CD0D89D");num seed = 0; // we may need a random seed value

// a random seed is only required for DSA and ECDSA, not RSAif (!key.isRSA()) num seed = num(cdk::getrand2(80));

key.Sign(num(digest), seed, sig);

To obtain an ASN.1 encoded digital signature from a cdk::Signature object, you mayuse the toasn1() function:

cdk::Signature sig; // contains signature to be extracted

// get an ASN1. encoded represention of the signaturecdk::str strSignature = sig.toasn1();

There are two ways to extract a digital signature in "raw" form. The first option is touse the toraw() method like this:

cdk::Signature sig; // contains signature to be extracted

// get a raw (binary) represention of the signaturecdk::str strSignature = sig.toraw();

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 332: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

326 Cookbook

The second method is to explicitly extract the signature components as shown here:

cdk::Key key; // contains signer’s private keycdk::Signature sig; // contains signature to be extracted

// get the raw signature component(s)num r,s;if (!key.isRSA())

r = sig.r; // we only need r for DSA and ECDSAs = sig.s;

// we can convert r and s to hex-encoded strings as follows:cdk::str strR, strS;if (!k1.isRSA()) strR = r.tostring().tohex();strS = s.tostring().tohex();

5.5.4.2 Validating

An ASN.1 encoded RSA, DSA or ECDSA digital signature can be loaded into a Sig-nature object and validated against a purported signer’s public key as follows:

cdk::Key key; // contains purported signer’s public keycdk::str digest; // contains message digest inputcdk::str strASN1Signature; // contains the ASN.1 encoded signature

// load the ASN.1 signature into a new Signature objectcdk::Signature sig;sig.load(strASN1Signature); // nonzero return value indicates error

// and attempt to validate itint i = key.SignCheck(num(digest), sig); // returns zero if validprintf("Signature is %s", i ? "INVALID!" : "valid");

To verify a signature represented as raw signature components (possibly obtained usingthe toraw() method described above), use the following:

cdk::Key key; // contains purported signer’s public keycdk::Signature sig; // contains signature to be verifiedcdk::str digest; // contains message digest

// explicitly load the relevant signature componentsif (!key.isRSA()) // we only need r for DSA and ECDSA

sig.r = r;sig.s = s;

int i = key.SignCheck(num(digest), sig); // returns zero if validprintf("Signature is %s", i ? "INVALID!" : "valid");

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 333: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.5 Handling Public and Private Keys 327

5.5.5 Handling Symmetric Keys

5.5.5.1 Wrapping With a Public Key

Suppose you have a recipient’s public key and wish to send him some encrypted data.The scheme most commonly used today is to encrypt the data with a random sessionkey and send the resulting ciphertext to the recipient along with the session key en-crypted, or "wrapped," with his public key. The following code fragment illustratesthis scheme:

cdk::Key pubKey; // this contains recipient’s public keycdk::str sessionKey; // this contains the random session key

// wrap the session keycdk::str wrappedKey; // output buffer for the wrapped keypubKey.Encrypt(sessionKey, wrappedKey);// nonzero return value indicates error

sessionKey can be used with AES or TDES to encrypt the data, then the ciphertext andwrappedKey are transmitted to the recipient.

5.5.5.2 Unwrapping With a Private Key

Once the recipient has received the ciphertext and wrappedKey produced by the aboveexample, he proceeds to decrypt, or "unwrap," the session key using his private key,then uses it to decrypt the data. The following code fragment illustrates this:

cdk::Key prvKey; // this contains recipient’s private keycdk::str wrappedKey; // wrapped key received from sender

// unwrap the session keycdk::str sessionKey; // output buffer for session keyprvKey.Decrypt(wrappedKey, sessionKey);// nonzero return value indicates error

The recipient now loads the unwrapped sessionKey into the appropriate cipher object(AES, DES, etc.) and decrypts the data.

5.5.6 Diffie-Hellman Key Agreement

Diffie-Hellman key agreement allows each of two communicating parties to privatelyderive a shared secret after simply exchanging their public keys. Subsequent com-munications can be made confidential by encrypting messages using a symmetric keyderived, in a previously agreed upon manner, from the shared secret. Since it is infea-sible for an eavesdropper to compute the shared secret, communications between thetwo parties remain secure.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 334: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

328 Cookbook

The code fragment below illustrates how to implement the DH protocol using a singleCDK function. It applies equally well to DSA keys and ECDSA keys, but cannot beused with RSA keys.

Note:

Using DSA keys (both based on the same parameter set!) in this example yieldsDiffie-Hellman in a prime-order subgroup of the multiplicative group of nonzeroelements in a field of integers modulo a large prime. This use conforms with ANSIX9.42 as well as RFC 2631, section 2.1.1.Using ECDSA keys (both based on the same underlying elliptic curve and choiceof base point!) yields Elliptic Curve Diffie-Hellman in the common elliptic curvegroup. This use conforms with ANSI X9.63.

At this time the CDK does not provide a particular key derivation function (KDF), i.e.,a function that turns the shared DH secret into a key for a particular symmetric cipher.RFC 2631, section 2.1.2 suggests one possible KDF using SHA-1 and the programmerwill have no trouble implementing that algorithm using the CDK’s SHA class.

// assume that Ann has her own key pair in k1 and Bob’s public key in k2cdk::Key k1, k2;// she computes:cdk::Point secretA = k2.pub * k1.getPrivate();

// assume that Bob has his own key pair in k3 and Ann’s public key in k4cdk::Key k3, k4;// he computes:cdk::Point secretB = k4.pub * k3.getPrivate();

// now, secretA = secretB, so Ann and Bob share a secret no eavesdropper// with only their public keys could compute

For information concerning the objects/methods used here see:

• cdk::Key

• cdk::RSA

• cdk::Cert

• cdk::Signature

• cdk::Chain

The next topic is Handling PKCS PDUs (including CMS).

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 335: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.6 Handling PKCS PDUs (including CMS) 329

5.6 Handling PKCS PDUs (including CMS)

The CDK provides methods for processing the popular PDUs ("protocol data units")defined by several PKCS standards documents and related RFCs. Among the supporteddata formats are:

• PKCS #7 Certificate Sets

• PKCS #8 Private Keys

• PKCS #10 Certificate Requests

• PKIX Certificate Request Message Format (CRMF)

• PKCS #12 Key Transport Packages

• IETF Cryptographic Message Syntax (CMS)

– Creating an EnvelopedData PDU

– Decrypting an EnvelopedData PDU

– Creating a SignedData PDU

– Validating a SignedData PDU

• Password Based Encryption (PKCS #5 PBE)

Note:

The certificates and other PDUs in all of the examples below are represented asbase64-encoded octet strings so that they could be included as string literals in thesource code. If you are loading a PDU from a file and are unsure whether the datais base64-encoded or not, you should test for the encoding wrapper and, if one ispresent, remove it before attempting to load the data.To decode a (possibly base64-encoded) PDU stored in a cdk::str object x, use astatement of the form:if(x[0]!=0x30) x = x.tobin64()

as shown below. (Note that the predicate (x[0]!=0x30) is true when the PDUbegins with the character ’M’ as it does when it is base64-encoded, whereas allbinary ASN.1 encoded PDUs under consideration here start with the tag ’\x30’for an ASN.1 BER/DER-encoded SEQUENCE.)

5.6.1 PKCS #7 Certificate Sets

PKCS #7 PDUs are often used to transport a set of certificates, an often unorderedcollection of possibly unrelated X.509 certificates.

The cdk::Chain class provides several methods for creating, parsing, and manipulatingPKCS #7 PDUs for the purpose of certificate transport. For example, a certificate set

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 336: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

330 Cookbook

can be sorted into an ordered certificate path (discarding unrelated certificates). Rootand leaf (end-user) certificates can also be identified and extracted from the set.

The first example in this section shows how individual certificates may be extractedfrom a PKCS #7 PDU:

cdk::str strPKCS7; // contains the PKCS #7 PDU to be parsed

// parse the PKCS #7 PDU into a new Chain objectcdk::Chain chn; // buffer for the certificate chaincdk::parsep7(strPKCS7, chn); // nonzero return value indicates error

// extract the first two certificates in the chaincdk::str strCertA, strCertB; // buffers for the individual certificatesstrCertA = chn.index(0);strCertB = chn.index(1); // empty string indicates no more certificates

A PKCS #7 PDU containing a chain of one or more certificates may be created asfollows:

cdk::str strCertA = // a sample base64-encoded certificate"MIICwjCCAiugAwIBAgIBATANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQGEwJVUzEL""MAkGA1UECBMCSUwxETAPBgNVBAcTCE9hayBQYXJrMQwwCgYDVQQKEwNJU0MxEDAO""BgNVBAsTB0RlbW8gQ0ExHDAaBgNVBAMTE0NlcnRpZmljYXRlIE1hbmFnZXIwHhcN""MDMwNjI0MDUwMDAwWhcNMDUwNjI0MDUwMDAwWjBrMQswCQYDVQQGEwJVUzELMAkG""A1UECBMCSUwxETAPBgNVBAcTCE9hayBQYXJrMQwwCgYDVQQKEwNJU0MxEDAOBgNV""BAsTB0RlbW8gQ0ExHDAaBgNVBAMTE0NlcnRpZmljYXRlIE1hbmFnZXIwgZ8wDQYJ""KoZIhvcNAQEBBQADgY0AMIGJAoGBAMPYg8Up8s3CAJICbNyW/CTxbj4yzaA8ZbcX""2t969MysICe0EI2/Z2xuTXuhY6hjFi6B9d/+yVLB17zHqpEpSbafCQMZvGc1pe7u""bcf+4wFtt5yRo7WRz6y/bMUnpCB+TlT++w8ZKTLwXNNLgAAIRC8WtawKx/c7aCJo""lekN65VXAgMBAAGjdjB0MBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTAD""AQH/MB0GA1UdDgQWBBSUr9rVPeS8n/o4spfRv3Kp+4PGCTAfBgNVHSMEGDAWgBSU""r9rVPeS8n/o4spfRv3Kp+4PGCTAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQEF""BQADgYEAnsGoKxDrTn+BGZNxUTjbVwv6Lkk9xr2R2y68JiUY48fGgu5IzO9QSsl7""UmqLAZCryOY08lNxduVXyiwRHSt8088v+6qvCgAjhxTZIn8EFOECom6tKTV9Hp6h""dU+z5aFhfSgJRKL0SzTrBg8P2/LIqMMotKBoQWqjnB+aP2d4jgk=";

cdk::str strCertB = // another base64-encoded certificate"MIID2DCCA0GgAwIBAgIBFzANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQGEwJVUzEL""MAkGA1UECBMCSUwxETAPBgNVBAcTCE9hayBQYXJrMQwwCgYDVQQKEwNJU0MxEDAO""BgNVBAsTB0RlbW8gQ0ExHDAaBgNVBAMTE0NlcnRpZmljYXRlIE1hbmFnZXIwHhcN""MDMwNjI3MTk0ODU3WhcNMDQwNjI2MTk0ODU3WjBJMREwDwYDVQQMEwhNaXggQ2Fz""ZTEOMAwGA1UEAxMFVGVTVDMxJDAiBgkqhkiG9w0BCQEWFXRlc3QzQGluZm9zZWNj""b3JwLmNvbTCCAbYwggErBgcqhkjOOAQBMIIBHgKBgQCT6JZdr9nf7P0AtGa2j5Dq""aK9dyf7ZFSeNGzoTdHHmVZbDf+0MeCn/j4Mx+BonAEOOzcwJRH3Dl8aF85cpT3Ir""zEhK7fKL7SWqqzXTWmXbH9YsnXulWET+sflAHmcTQJM+5DxU5NxFlADXrWEki4Oi""Ykg1sx//LZWVpbkLJ25E+QIVALtd/kLeEVwA217xsDiDRNbBVIWtAoGAaSefjrq4""Do8k8BhGIZZjbEwiVGTwEz4PLyHnu+0dhT8G65SahoUKMKm1ss6oMOqtAOe99h68""gcxB3rr/G1v9nyqksRMpsTw9xpURJ/vIa001M4I7+XpY3i/x+cmzF3ujSU7V4AA4""Pb1qaZ1XiVSPzvUHNo5L5m7rDwh1c4y8/MUDgYQAAoGAAJevjq95fOwS9l3Cr1xq""KIftJsWoT16u37VhiRfGEq+/JEkDjBkC22S10E7Iyv7p75Lv617N+2pOYQRWtcxp""U169I60gxNvW6c2eLXHA+d9vKvaIqjmsYP9K/poqMJ2sdK50OQJxId4xOWiN9KLp""BicXOLjcp1VHE1MaNST1fQWjgZUwgZIwEQYJYIZIAYb4QgEBBAQDAgWgMA4GA1Ud""DwEB/wQEAwIF4DAYBgNVHREEETAPgQ1hbGljZUBpc2MuY29tMB8GA1UdIwQYMBaA""FJSv2tU95Lyf+jiyl9G/cqn7g8YJMDIGA1UdCQQrMCkwEgYJYIZIAWUCAgFEMQUW"

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 337: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.6 Handling PKCS PDUs (including CMS) 331

"A0FCQzATBgpghkgBhvhCAwEEMQUWA1ImRDANBgkqhkiG9w0BAQUFAAOBgQCq778P""0yNeutqWu7pomHJ8yWZ7ZC2w8njvOLLJoECaaP5j9xt6hRdyCqIfzx3hVWxv1VOb""dHgEfNViMFPaURYRJWbfX0Gn7+DJ9Lluby6prXPm0rTIZ4GdRCBA58dhn7ct5itc""YorKfy79SaeumDvsjIvbe7iR6WO5rDxuVChaBA==";

// decode the certificates if they are base64-encoded (as these are)if (strCertA[0] != 0x30) strCertA = strCertA.tobin64();if (strCertB[0] != 0x30) strCertB = strCertB.tobin64();

// add the binary ASN.1 encoded certificates to a new Chain objectcdk::Chain chn; // output buffer for certificate chainchn.add(strCertA);chn.add(strCertB);

// construct a PKCS #7 PDU containing the certificate chaincdk::str strPKCS7 = cdk::makep7(chn);if (+strPKCS7 == 0) return -1; // empty string indicates error

PKCS #7 (CMS Version 1.5) is specified in RFC 2315 but has been obsoleted by RFC3852.

5.6.2 PKCS #8 Private Keys

PKCS #8 support in the CDK is limited to the creation and parsing of password-protected private key packets. The code below shows how to extract a private key froma Key object and put it into a PBE-protected PKCS #8 PDU that is TDES-encryptedwith a user-supplied password:

cdk::Key key; // contains private key to be transportedchar *pwd = "abcdefgh"; // user password for the PDU

// extract the algorithm ID and private key from the Key objectcdk::str strAlgID, strPrv;strAlgID = key.asn1parameters(1,0);strPrv = key.asn1private();

// create a TDES-encrypted PKCS #8 PDU containing that datacdk::str strPKCS8 = makep8(strAlgID, strPrv, pwd);if (+strPKCS8 == 0) return -1; // empty string indicates error

Using the CDK to decrypt and parse an encrypted PKCS #8 private key is also easy.This example shows how to parse the PKCS #8 PDU created above and load its privatekey into a cdk::Key object:

cdk::str strPKCS8; // PKCS #8 PDU to be decrypted and parsedcdk::str strAlgID, strPrv; // buffers for algorithm ID and private keychar *pwd = "abcdefgh"; // user password for the PDU

// use pwd to decrypt the PKCS #8 PDU, then parse itcdk::parsep8(strPKCS8, pwd, strAlgID, strPrv);

// nonzero return value indicates error

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 338: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

332 Cookbook

// insert the algorithm ID and private key into a new Key objectcdk::Key key;key.loadoid(strAlgID); // nonzero return value indicates errorkey.loadprv(strPrv); // nonzero return value indicates error

5.6.3 PKCS #10 Certificate Requests

The CDK can also handle PKCS #10 certificate requests. The following code showshow to create and sign a PKCS #10 PDU and then how to parse it.

cdk::Key key; // key to be included in the requestcdk::DName dn; // subject DN to be included in the requestdn.cname = "John Doe";dn.org = "XYZ Corp.";dn.country = "US";

// extract the algorithm ID and *public key* from the Key objectcdk::str strPub, strAlgID;strAlgID = key.asn1parameters(1,0);strPub = key.asn1public();

// create a request body with that public key and subject DNcdk::str tbsP10 = makep10raw(dn.toasn1(), strAlgID, strPub, "");

// create the PKCS10 PDU by self-signing with the private keycdk::str strP10;key.asn1sign(tbsP10, num(cdk::getrand2(80)), strP10);

// nonzero return value indicates error

// parsing a PKCS #10 PDU also validates its signaturecdk::str strDN; // output buffer for subject DNcdk::str strAttr; // output buffer for attributesparsep10(strPKCS10, strDN, strAlgID, strPub, strAttr);

// nonzero return value indicates parsing or validation error

PKCS #10 is specified in RFC 2986.

5.6.4 PKIX Certificate Request Message Format (CRMF)

The CRMF is a newer alternative to the certificate request syntax specified by PKCS#10.

You can parse a CRMF PDU as follows:

cdk::asn aDN, aOID, aPub, aAttr;

// convert request PDU to binary and parsecdk::str req = cdk::asn(request).tobin();cdk::parse_crmf(req, aDN, aOID, aPub, aAttr);cdk::parsedname(aDN, dn, 2); // convert DN to text

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 339: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.6 Handling PKCS PDUs (including CMS) 333

cdk::Key key;key.loadoid(aOID);key.loadpub(aPub);

keysize = key.bits();if (key.isRSA()) keytype = 1;else if (key.isDH()) keytype = 2;else if (key.isEC()) keytype = 3;else keytype = -1; // unknown key type

CRMF is specified in RFC 4211 which obsoleted RFC 2511.

5.6.5 PKCS #12 Key Transport Packages

The next code fragment shows how to parse a PKCS #12 "PFX" PDU and then recreateit.

cdk::str strP12 = // a sample base64-encoded PKCS #12 PDU"MIIGQgIBAzCCBggGCSqGSIb3DQEHAaCCBfkEggX1MIIF8TCCAt8GCSqGSIb3DQEH""BqCCAtAwggLMAgEAMIICxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIPtPP""DiTkLIQCAgQAgIICmCAJ/jf5UOduGWpozCah9dLjcJdG5xb3FlHBaN1c35VDOGK3""1BZUQDvGsYttBASLD+wXY3i/MnEAwOX6c4EfL17JQtIJfE7mCAukaqUbJtLtQsvJ""7JMMwfUhRkEWQA60rJV2/CaL2bewy1MIFrduf02ImTNbB20059/ewn8Ya7cXZlrH""bjWhv0OjeYWvBstBRCZkz2w0Yyu9F8KGVS0HHDuiBUMU0gMBnp7COUumzZ9hzYGi""GNz0VivzX86cL/wiNvSyTpbZFsOw0+NxLdG1NlSbwbFu2Ay9uQI9xh886odnsLsn""u9fTpkFFlBTEwyawP8UUEjMNiXo+SVX93xGi7wfoe9HmpXBsvQ4suPzqs8j8SJ8b""9pOKF40eb48GxSYUbPJ6kfBan45Doe7ypkApTpejAebVLz00u5yH+A3HiJm+Okk2""Hzq+/Rh/vcY2+jjimZfV0qVVPLyDKTSWLgo7D9L4dCeeWU3VCdAbeyUKnx2V8Av9""qU0q8qeDLGaXGyxZ24G7UQzaaUIIOn0wUFSjupGFctMPXz3/QvkUQgSuLKRhMWnk""e6UNA2N0y5gMMmcfNh6n226m6t7lCce3KXRcCAZr0IJMpdldO7tft0v2dqo6reuE""x3bv5I3ink0SJSz0xZr92p9dcqcO067PIZ3TjQaLyziYJUPvyo53Z7udPB8qTUYn""v9U+3Ovjh2eGQ/5KvFathlAPav+Styn4w5LIKPDiyxXfrADeELEYOgV9AauDVaiC""vrWESXbgTbCaMcYTrWDH4tWlhXLtBbTSlemAVClUa1BvSGRvAEJiF+46S1oESwQx""ZTw0uBtmiuVtccRrzhS4YvxAgsBUqstd3B45RCdi8v0uECAzEYBkfdiW7ZlfxQKa""q2s4oC0wggMKBgkqhkiG9w0BBwGgggL7BIIC9zCCAvMwggLvBgsqhkiG9w0BDAoB""AqCCAqYwggKiMBwGCiqGSIb3DQEMAQMwDgQIL5knnoi6f/8CAgQABIICgCHYGIzu""7kzK8eynvtCUzMxyrJ/k/BHnEDJ70TADRxfgn/8GylDGvxblJZaaa+W5XF0pIf7/""C7ZbBRzoqzhkK2IbH1jKGtFOfP81kxpw9pLW2A01AT0rT62uEDleP1EbPKFgehBm""FPp/F0y06UbewfluW6nqky5feqmTQJWBWv8ctRsH2JeOxoI4MkEPOoOYUeViPM3w""YIzon6GxiNiUP+7l4Eh+WhM2ViKGRr/m02wWvgL9mnkj/aOqvPN+o7i6Up6+oVRz""sWfUyQip5V3n+J7y1an+lS3nZDjxCXy0f4O9DyNV/96KMrQDFCbzRVBQNqttChuK""yqsai+HQH5+xywiwCSQEfMnVElZUB2O+nCZ8Dd3PbXuZ0bl3getc7YfgOhAI8+hX""HXKDzwmGl9VYwctAzqd/LLVG+sg4zJBkideLB8fW9ciE4LOsa6QeVGNSLwn61lGJ""AMxIiIK19xFmnvqyeBhF1fWmPJhcnkUaWNfbmSco+u/156B5vKu6cBO4i/+/oG3M""lOAyMV+jPB1YGOo8p1K5PiC0LODHKpbinK+SM3NYx1RbxEn+8rNQcOURvE0cchxs""C/dqV00w/9lfA797mElW5ToOYFJot3G5NWRxJ6tf1myrMJ7VUSsJFN1aOUPj+AL5""U5Dgh715z5ji+ExHLolJabsCkTd76137NoNPR8/MvWhRY94qdJABU55kyjjJPlJU""wN0kE/At+wjSCXkI589qnuSJHr37X3UtUbTeK/r0QiL6ennxIkwUDqsiHR/ZAEy1""Wdwjh9ij4Y9ogYB7aePtlZSqfO5FGHbgGs8EvOmFwotXM5mYCaXHMZE4We7KBto8""Clcx/7TxvVH0OgUxNjAPBgkqhkiG9w0BCRQxAh4AMCMGCSqGSIb3DQEJFTEWBBQw""MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMCEwCQYFKw4DAhoFAAQUf8HYKKKVoyHkyeOX""hpvt5t+Kn4IECCYQiCMLyK+cAgIEAA==";

// decode the PKCS #12 PDU if it is base64-encode (as this one is)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 340: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

334 Cookbook

if (strP12[0] != 0x30) strP12 = strP12.tobin64();

cdk::Chain chn; // output buffer for a certificate chaincdk::str crl; // output buffer for a certificate chaincdk::str algID; // output buffer for the algorithm IDcdk::str prvKey; // output buffer for the private keychar *password = "abcdefgh"; // user’s passsword for this PDU

// parse the PKCS #12 PDU and decrypt its private keycdk::parsep12(strP12, password, chn, algID, prvKey, crl);

// nonzero return value indicates parsing or password error

// locate end user’s certificateint nEndUserCert = chn.find(Chain::user);

// return value of -1 indicates end-user certificate not found

// load the certificate into a new Cert objectcdk::Cert cert; // output buffer for certificatecert.load(chn.index(nEndUserCert));

// load the end-user key pair into a new Key objectcdk::Key key;key.loadoid(cert.subject_oid);key.loadpub(cert.subject_pub);key.loadprv(prvKey);

// the CDK can also be used to create a PKCS #12// first parameter can either be the end user’s certificate or an entire chaincdk::str strP12 =

makep12(chn.certs, k1.asn1parameters(1,0), k1.asn1private(), password, "", "");if (+strP12 == 0) return -1; // empty string indicates error

5.6.6 IETF Cryptographic Message Syntax (CMS)

5.6.6.1 Creating an EnvelopedData PDU

To create an AES-encrypted CMS EnvelopedData PDU (following PKCS #7), you mayuse class CMS1 as follows:

int CMSEncrypt(const cdk::str &recips, const cdk::str &msg, cdk::str &p7m){

/*input parameters:recips: a concatenated list of recipient certificatesmsg: the message to be encryptedp7m: an output buffer for the ciphertext

*/// obtain an random key and IVstr key = getrand2(16), iv = getrand2(16);

// instantiate and initialize a CMS1 objectcdk::CMS1 cms;cms.enveloped = true;cms.recip_cer = recips;

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 341: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.6 Handling PKCS PDUs (including CMS) 335

// create the encrypted body and DER-encode it as per PKCS #7if (cms.encrypt(key,iv,msg,1)) return -1;p7m = cms.make();

return 0;}

Note that the length of the key determines the version of AES that is employedby cdk::CMS1::encrypt(): 16 bytes tranlates into AES-128, 24 into AES-192, and32 into AES-256. For TDES encryption, simply omit the fourth parameter in thecdk::CMS1::encrypt() call, in effect letting it default to 0.

NOTE: If the input data is properly MIME-encoded, the p7m PDU output by CMSEn-crypt() can itself be MIME-encoded to produce a true S/MIME message. The use ofCMS in S/MIME is specified in RFC 3851.

5.6.6.2 Decrypting an EnvelopedData PDU

Given an encrypted CMS PDU (EnvelopedData) and a user’s certificate and private key(in the form of a password-encrypted PKCS #8 PDU), one might go about decryptingthe PDU as follows:

int CMSDecrypt(cdk::str &p7m, cdk::str &cert, cdk::str &p8, cdk::str &pwd, cdk::str &msg){

/*input parameters:p7m: the ciphertext to tbe decryptedcert: the user’s certificatep8: the user’s password-encrypted private keypwd: the user’s passwordmsg: an output buffer for the plaintext

*/// instantiate a CMS1 object and load the ciphertext datacdk::CMS1 cms;cms.load(p7m); // this parses out recipient info

// obtain user’s key type and private key from a PKCS #8 PDUcdk::asn oid, prv;cdk::parsep8(p8, pwd, oid, prv);

// return error if user is not a recipientcdk::Chain chn(cert);cdk::asn cmsCert, cmsPDU;if ( chn.findmatch(cms.recips, cmsPDU, cmsCert) != 0 )

return -1;

// otherwise decrypt PDUcms.decrypt(cmsPDU, oid, prv);msg = cms.data;return 0;

}

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 342: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

336 Cookbook

5.6.6.3 Creating a SignedData PDU

The following code shows how use a CMS1 and Signer object to create an opaqueCMS SignedData PDU:

int CMSSign(cdk::str &cert, cdk::str &p8, cdk::str pwd, cdk::str &msg, cdk::str &p7s){

/*input parameters:cert: the user’s certificatep8: the user’s password-encrypted private keypwd: the user’s passwordmsg: the message to tbe signedp7s: an output buffer for the signed CMS PDU

*/// obtain user’s key type and private key from a PKCS #8 PDUcdk::asn oid, prv;cdk::parsep8(p8, pwd, oid, prv);

// set up a Key object with the user’s private keycdk::Key key;key.loadoid(oid);key.loadprv(prv);key.genpub();

// instantiate and initialize a CMS1 objectCMS1 c;c.enveloped = false; // sign, don’t encryptc.data = msg;c.chn.certs = cert;

// create the signed body and DER-encode it as per PKCS #7PRNG r;Signer s;if ( s.make(msg, cert, key, num(r.gens(20)), c.signers) ) return -1;p7s = c.make();

return 0;}

5.6.6.4 Validating a SignedData PDU

A CMS SignedData PDU can be verified as follows:

int CMSVerify(cdk::str &p7s, cdk::str &msg, cdk::str &cert){

/*input parameters:p7s: the SignedData PDU to be validatedmsg: the message data that was signedcert: output buffer for the signer’s certificatereturns 0 if signature is valid

*/CMS1 cms; // instantiate a CMS1 object

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 343: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.6 Handling PKCS PDUs (including CMS) 337

// load PDU and return error if it can’t be parsedif ( cms.load(p7s) ) return -1;

// return an error if it’s EnvelopedData (or handle it!)if ( cms.isEnveloped() ) return -1;

// parse out signer info and cert; abort if not found in PDU or invalidasn sInfo, aCert=cert;if ( cms.chn.findmatch(cms.signers,sInfo,aCert) != 0 )

return -2;

Signer s;if (s.load(sInfo)) return -3;

// re-hash data and compare with message digest in PDUif (HASH(SHA,cms.data,1) != s.messageDigest1)

return -4;

cdk::TimeT date = s.signingTime;int i = checksignhash(cert,num(s.messageDigest2),s.signature1);

int err = 0;if (i) err = ((i == CDK_CERT_EXPIRED) ? -5 : -6);return err;

}

See RFC 3852 for more information on CMS message formats. The original descrip-tion of PKCS #7 is in RFC 2315.

5.6.7 Password Based Encryption (PKCS #5 PBE)

The CDK provides support for generating session keys from passwords based on PKCS#5 and PKCS #12. cdk::genkeyp12() generates a session key of the requested lengthbased on a password according to the PKCS #12 standard. cdk:genkeyp5() generates asession key of the requested length based on a password according to PKCS #5. Theiruse is shown below:

// Generate a 192-bit session key according to PKCS #12cdk::str strSession = cdk::genkeyp12("password", cdk::getrand2(8), 24, 1024, 1);// Generate a 16-byte IV according to PKCS #12cdk::str strIV = cdk::genkeyp12("password", cdk::getrand2(8), 16, 1024, 2);// Generate a 192-bit MAC key according to PKCS #12cdk::str strMAC = cdk::genkeyp12("password", cdk::getrand2(8), 24, 1024, 3);

// Generate a 192-bit session key according to PKCS #5cdk::str strSession2 = cdk::genkeyp5("password", cdk::getrand2(8), 512, 24);

In order to recreate the session key you need the password, salt, and iterations used tobegin with. In general the salt and iterations are passed along with the encrypted dataso that the recipient need only enter the password to decrypt the data.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 344: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

338 Cookbook

PKCS #5 is specified in RFC 2898.

The next topic is Pseudorandom Numbers.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 345: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.7 Pseudorandom Numbers 339

5.7 Pseudorandom Numbers

The CDK provides methods for generating pseudorandom numbers and for derivingsymmetric keys from passwords.

While class PRNG can be used direectly for greatest efficiency, the global functionscdk::getrand1() and cdk::getrand2() simplify access to the CDK’s pseudorandom num-ber generation routines.

The function cdk::getrand2() calls cdk::PRNG::gens() to obtain FIPS 140-1 compli-ant pseudorandom numbers and should be used for all cryptographic purposes. Theimplementation of cdk::getrand2() is given as follows:

cdk::str getrand2(int n){

PRNG prng;return prng.gens(n);

}

The faster cdk::getrand1() function provides non-FIPS 140-1 pseudorandom numberssuitable for non-cryptographic uses.

For convenience, the samples provided in the "Cookbook" section of this documenta-tion regularly make use of cdk::getrand2(). However, this approach may not providethe best performance for your application. cdk::getrand2() is slow because it gatherscomplete system state information with each invocation (i.e., with each instantiationof the temporary PRNG object). A more efficient approach is to instantiate a singlecdk::PRNG object and to call its cdk::PRNG::gens() method whenever pseudorandomnumbers are required. For more details on this issue, see the documentation on classcdk::PRNG.

The next topic is Implementing a Simple TLS Client.

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 346: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

340 Cookbook

5.8 Implementing a Simple TLS Client

This section illustrates use of the TLS class to implement a simple SSL or TLS client.For background information, we refer the reader to RFC 2246.

First, assume that we have instantiated a TLS object, set up a pseudorandom numbergenerator, and have all certificates required for client and server authentication:

TLS tls; // instantiate a %TLS objectPRNG prng; // and a PRNGcstr rootCerts; // trust anchors for server certificate authenticationcstr userCerts; // user’s certificate chain for client authentication

To initialize the TLS object, we:

• specify the minor TLS version number and preferred cipher suite,

• provide seeds for the required pseudorandom numbers, and

• (optional) register a signature callback for client authentication

int Init(int cipher, int minor, TokenSignCallback tcb, void *tokeninfoptr){

tls.setcipher(cipher,minor);tls.setrand(prng.gens(46),prng.gens(28),prng.gens(20),cdk::timegmt());tls.sign = tcb;tls.tokeninfoptr = tokeninfoptr;return 0;

}

Our basic messaging functions assume the existence of an open communications chan-nel to the server. Here an undocumented object (’sock’) will provide that functionalityvia its Send() and Recv() functions. Using sock, SendRecv() sends anything that mightbe in the TLS client buffer, then populates the TLS server buffer with whatever datahas been received from the server:

int SendRecv(){

// returns: 0=did nothing, 1=something, 2=errorif (+tls.c.buf){int i = sock.Send(tls.c.buf);if (i != +tls.c.buf) return 2;tls.c.buf = 0;return 1;

}Sleep(200);str x = sock.Recv();tls.s.buf += x;return !!+x;

}

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 347: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.8 Implementing a Simple TLS Client 341

Get() returns a complete communications record from the server, decrypting it if nec-essary:

str Get(){

if (m_bHTTPS){

for (;;){

if (isBad()) return 0;str x, y;int i = tls.parse(x,y);if (i == 0){tls.s.buf = y;if (tls.unwrap(x,y)) return 0;return y;

}if (i == 2) break;Sleep(90);tls.s.buf += sock.Recv();

}}else{

Sleep(90);str y = sock.Recv();return y;

}return 0;

}

To connect to a server and ’GET’ a page, we simply:

• initialize the socket,

• load the user certificate chain (if client authentication is required),

• perform the initial handshake with dorecs() and SendRecv(),

• encrypt our GET request (if we’re doing HTTPS),

• transmit the encrypted packet, and

• Get() a response from the server

str GETpage(cstr addr, cstr file, int port){

int i;sock.initconnection(addr,port);if (m_bHTTPS){

tls.load(userCerts);for (;;)

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 348: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

342 Cookbook

{i = tls.dorecs();if (i > 1) return error(tls.lasterror);if (tls.isHot()) break;if (tls.isBad()) return error(tls.lasterror);i = SendRecv();if (i > 1) return error(errProtocolFailure);

}i = 0;// validate the server certificate:if (+rootCerts)i = CheckCA(rootCerts,tls.s.cer);

else if (cbvalidatecert != NULL){cdk::tokenop t;t.cer = tls.s.cer;i = cbvalidatecert(t);

}if (i) return error(i);

}str data = str("GET /") + file + " HTTP/1.0\r\n\r\n";str x = data;if (m_bHTTPS) x = tls.wrap(data);i = sock.Send(x);if (i < 0) return error(errProtocolFailure);

x = 0;long t = timegmt();do x += Get(); while (!isComplete(x) && t + 30 > timegmt());return x;

}

POSTing is similar. We:

• initialize the socket,

• load the user certificate chain (if client authentication is required),

• perform the initial handshake with dorecs() and doIO(),

• encrypt our HTTPS POST request (if we’re doing HTTPS),

• transmit the encrypted packet, and

• Get() a response from the server

str POSTpage(const str &addr, const str &file, const str &postdata, int port){

int i;sock.initconnection(addr,port);if (m_bHTTPS){tls.load(userCerts);for (;;){

CDK 7.0 - Information Security Corporation - Jul 18, 2006

Page 349: ISC CDK 7 Reference Manual · 2.1 cdk Namespace Reference ... • message digests: SHA-1, SHA-256 ... const str &pub, const str &attributes) Create an ASN.1 encoded PKCS#10 ...

5.8 Implementing a Simple TLS Client 343

i = tls.dorecs();if (i > 1) return error(tls.lasterror);if (tls.isHot()) break;if (tls.isBad()) return error(tls.lasterror);i = SendRecv();if (i > 1) return error(errProtocolFailure);

}i = 0;// validate the server certificate:if (+rootCerts)

i = CheckCA(rootCerts,tls.s.cer);else if (cbvalidatecert != NULL){

cdk::tokenop t;t.cer = tls.s.cer;t.tokeninfoptr = tls.tokeninfoptr;i = cbvalidatecert(t); // 0 OK non-zero bad.

}if (i) return error(i);

}char szPD[32];sprintf(szPD, "%d", postdata.length());str header = str("POST /") + file + str(" HTTP/1.0\n")

+ str("Content-type: application/x-www-form-urlencoded\n")+ str("Content-length: ") + str(szPD)+ str("\n\n");

str data = header + postdata;str x = data;if (m_bHTTPS) x = tls.wrap(data);i = sock.Send(x);if (i < 0) return error(errProtocolFailure);

x = 0;long t = timegmt();do x += Get(); while (!isComplete(x) && t + 30 > timegmt());return x;

}

In both GETpage() and POSTpage() we used the following auxiliary function to deter-mine when a message from the server is complete:

int isComplete(str a){

int start = a.find("\r\n\r\n");if (start < 0) return 0;int i = a.find("Content-Length: ");if (i >= 0) return +a >= start + 4 + atoi(a.c_str()+i+16);if (+a > start && a[start] == 0x30)

return asn(a.skip(start)).isParseable();return a.find("</html>") >= 0 || a.find("</HTML>") >= 0;

}

See RFC 2246 for more information.

CDK 7.0 - Information Security Corporation - Jul 18, 2006