Key Struct Reference

#include <pk.h>

Inheritance diagram for Key:

Inheritance graph
Collaboration diagram for Key:

Collaboration graph

Detailed Description

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

Using Class Key

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

Generating RSA Keys

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

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

Generating DSA/DH/ECDSA/ECDH Keys

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

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

Using Existing Key Pairs

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

  Key()            // instantiate a Key object
  loadoid()        // specify key type and size
  loadprv()        // load ASN.1 DER-encoded private key components
  loadpub()        // load ASN.1 DER-encoded public key components

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

Once generated or loaded, key components may be accessed using the following member 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

Implementing Diffie-Hellman Key Agreement

Suppose that two parties, named Alice and Bob, wish to establish a common secret key using a insecure communications channel. (We'll assume they have previously agreed upon 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 channel. 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 and make those certificates available to each other by publishing them in a public repository.)

PHASE II: Alice now computes the common Diffie-Hellman secret by loading Bob's public key into a Key object and raising it to her private exponent (using the modular exponeniation 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();

Now Alice and Bob both possess the (full) Diffie-Hellman secret and can apply a previously 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,
  crlSign = 0x02,
  encipherOnly = 0x01,
  usageAll = 0xFF
}
 keyUsage bit masks More...

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.
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 () const
 Get an ASCII description of this object's key type and size.
int DLGetRawPublic (num &x, num &y) const
 Get 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 () const
 Get this key's "type.".
int bits () const
 Get the "size" of the key in this object.
int rawsiglength () const
 Get the length in bytes of a raw signature associated with this key.
num getPrivate () const
 Get the (raw) private key in this object.
str asn1private () const
 Get the ASN.1 encoded private key in this object.
str asn1public () const
 Get the ASN.1 encoded public key in this object.
str asn1parameters (int full=1, int withhash=1) const
 Get the ASN.1 encoded parameters in this Key object.
num order () const
 Get the order of this key's underlying Abelian group.
num A () const
 Get the first coefficient in the equation for this object's underlying elliptic curve.
num B () const
 Get the second coefficient in the equation for this object's underlying elliptic curve.
Sanity Checks
int check () const
 Check 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 FIPS 186-2.
Key Generation
int RSAkeygen (const str &seed, int nbits=1024, const num &exponent=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) const
 Perform modular exponentiation with this object's private key (for DH or ElGamal).
Encryption and Decryption
int Encrypt (const str &a, str &x) const
 Encrypt (or wrap) a specified buffer using this object's public key.
int Encrypt (const str &a, const str &seed, str &x) const
 Encrypt (or wrap) a specified buffer using this object's public key.
int Decrypt (const str &a, str &x) const
 Decrypt (or unwrap) a specified buffer using this object's private key.
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) const
 Sign the specified message digest using this object's private key.
int asn1sign (const str &msg, const num &krand, str &sig) const
 Produce an ASN.1 DER-encoded signature over a specified message.
int SignCheck (const num &hash, const Signature &sig) const
 Check the validity of a specified signature against this object's public key.
int SignCheck (const num &hash, const str &sig) const
 Check the validity of a specified signature against this object's public key.
Useful Predicates
bool hasPublic () const
 Predicate used to determine whether this object contains a public key.
bool isRSA () const
 Predicate used to determine whether this object contains an RSA key.
bool isDH () const
 Predicate used to determine whether this object contains an DH/DSA key.
bool isEC () const
 Predicate used to determine whether this object contains an elliptic curve key.
bool isChar2 () const
 Predicate used to test whether this object is an elliptic curve key over a field of characteristic 2.
bool permit (int flag) const
 Predicate used to test keyUsage bit settings.
Conversion Function
template<class T>
to () const
 Convert this key object into an object of type T.

Data Fields

int usage
 keyUsage extension
str keytype
 key type (e.g., gRSA, gDSA, gECP, or gEC2)
int hashtype
 hash type (e.g., hSHA1)
Point gen
 group generator (base point)
Point pub
 public key
int cofactor
 cofactor (EC only)
RSA rsai
 RSA key components.


Member Enumeration Documentation

anonymous enum

keyUsage bit masks

Enumerator:
digitalSignature  = 0x80
nonRepudiation  = 0x40
keyEncipherment  = 0x20
dataEncipherment  = 0x10
keyAgreement  = 0x08
keyCertSign  = 0x04
crlSign  = 0x02
encipherOnly  = 0x01
usageAll  = 0xFF


Constructor & Destructor Documentation

Key (  )  [inline, explicit]

Constructor.

Remarks:
Modifies: hashtype = hSHA1, usage, m_nDoPWCC

virtual ~Key (  )  [inline, virtual]

Destructor.

Remarks:
All key components are stored in objects whose destructors zeroize them.


Member Function Documentation

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.

int alg (  )  const

Get this key's "type.".

Returns:
an algorithm identifier for the key type: gRSA, gDSA, gECP, or gEC2

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

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.

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.

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 supplying a TBSCertificate (resp. TBSCertList) PDU as the actual msg parameter. After the call, sig will contain the desired X.509 certificate (resp. CRL).
Returns:
0 (success)
CDK_ERROR_STATE
CDK_PRVKEY_CANNOT_FIND
CDK_INVALID_KEYUSAGE
CDK_INTERNAL_ERR
CDK_INVALID_SIGNATURE

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.

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

int check (  )  const

Check the consistency of the keypair in this object.

Returns:
0, if key pair is OK
CDK_KEYPAIR_INCONSISTENT
Remarks:
This function also performs appropriate sanity checks, such as primality testing, where appropriate.

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 FIPS 186-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 OK
non-zero otherwise

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_STATE
CDK_PRVKEY_CANNOT_FIND
CDK_KEY_INVALID_USAGE

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 public key)
y an output buffer for the y coordinate of the EC public key (receives 0 in the DSA/DH case)
Returns:
0 (success)
CDK_INVALID_KEYTYPE
CDK_ERROR_STATE

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 with PRNG::gens(40))
strOID an ASN.1 DER-encoded OID specifying the DSA/ECDSA parameters to be used.
Returns:
0 (success)
CDK_ERROR_STATE
CDK_KEYPAIR_INCONSISTENT

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

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
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 each case.
Returns:
0 (success)
CDK_ERROR_STATE
CDK_KEY_INVALID_USAGE

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 buffer
x an output buffer for the ciphertext
Remarks:
This function performs a deterministic computation in all cases. This means that the output is reproducable for the same input.
Returns:
0 (success)
CDK_ERROR_STATE
CDK_KEY_INVALID_USAGE

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_STATE
CDK_KEYPAIR_INCONSISTENT

num getPrivate (  )  const [inline]

Get the (raw) private key in this object.

Returns:
this object's private key

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

bool hasPublic (  )  const [inline]

Predicate used to determine whether this object contains a public key.

Returns:
true, if this object contains a public key
false otherwise

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

bool isChar2 (  )  const [inline]

Predicate used to test whether this object is an elliptic curve key over a field of characteristic 2.

Returns:
true, if this object is an elliptic curve key over a field of char 2
false otherwise

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 key
false otherwise

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 key
false otherwise

bool isRSA (  )  const [inline]

Predicate used to determine whether this object contains an RSA key.

Returns:
true, if this object contains an RSA key
false, otherwise

int loadoid ( const str oid  ) 

Load ASN.1 encoded parameters.

Parameters:
oid a str containing an ASN.1 encoded OID providing RSA/DSA/ECDSA parameters Modifies: hashtype, rsai, cofactor, priv, gen, pub
Returns:
0 (success)
2, 23 = parse error
3 = DSA parse error
4, 26 = unknown/unsupported alg
22 = ECDSA parse error

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

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_INVALID
CDK_PARSE_ERROR
CDK_INVALID_KEY_TOO_MANY_PRIMES (2, 3, or 4 prime keys only)

int loadpub ( const str pubk  ) 

Load an ASN.1 encoded public key.

Parameters:
pubk the ASN.1 encoded public key to be loaded
Returns:
0 (success)
CDK_KEY_INVALID
non-zero = failure

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_STATE
CDK_INVALID_SEED
CDK_INVALID_ALG_PARAMS
CDK_INVALID_ITERATION_COUNT

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.

bool permit ( int  flag  )  const [inline]

Predicate used to test keyUsage bit settings.

Parameters:
flag the bit setting (enum value) to be tested against this object's keyUsage
Returns:
true if flag is permitted
false otherwise

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 exponent
x an output buffer for the result (a raised to the private exponent in the underlying group)
Returns:
0 (success)
CDK_ERROR_STATE
CDK_INTERNAL_ERR

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

int RSAGetRawPublic ( num expo1,
num pq1 
)

Get the raw RSA public key from this object.

Parameters:
expo1 an output buffer for the public exponent
pq1 an output buffer for the public modulus
Returns:
0 (success)
CDK_ERROR_STATE
CDK_INVALID_KEYTYPE

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_STATE
CDK_KEYPAIR_INCONSISTENT

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_KEYTYPE
CDK_ERROR_STATE

void setdefaulthash (  ) 

Set the hashtype of this object to SHA-1.

Remarks:
Modifies: hashtype = hSHA1

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.

void SetPadding ( int  nPadding  )  [inline]

Set the RSA padding scheme to use when signing.

Parameters:
nPadding padding indicator: pkcs1 or x931

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

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

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 with num(gens(20))
sig the Signature object that is to receive the result
Returns:
0 (success)
CDK_ERROR_STATE
CDK_PRVKEY_CANNOT_FIND
CDK_INVALID_KEYUSAGE
CDK_INTERNAL_ERR
CDK_INVALID_SIGNATURE

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 be verified
Returns:
0 if public key could verify the signature
CDK_ERROR_STATE
CDK_INVALID_KEYUSAGE
CDK_INVALID_DIGEST
CDK_INVALID_PADDING
CDK_INVALID_SIGNATURE

int SignCheck ( const num hash,
const Signature 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 Signature object containing the signature to be verified
Returns:
0, if signature is valid
CDK_ERROR_STATE
CDK_INVALID_KEYUSAGE
CDK_INVALID_DIGEST
CDK_INVALID_PADDING
CDK_INVALID_SIGNATURE

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:
ISC Cryptographic Development Kit - User's Guide
ISC website
Questions? E-mail ISC technical support
Copyright© 2002-2006 Information Security Corp. All rights reserved.