?? cryptmch.c
字號:
/****************************************************************************
* *
* cryptlib Mechanism Routines *
* Copyright Peter Gutmann 1992-2002 *
* *
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "crypt.h"
#ifdef INC_ALL
#include "asn1.h"
#include "asn1objs.h"
#include "pgp.h"
#else
#include "keymgmt/asn1.h"
#include "keymgmt/asn1objs.h"
#include "envelope/pgp.h"
#endif /* Compiler-specific includes */
/****************************************************************************
* *
* Utility Routines *
* *
****************************************************************************/
/* The length of the input data for PKCS #1 transformations is usually
determined by the key size, however sometimes we can be passed data which
has been zero-padded (for example data coming from an ASN.1 INTEGER in
which the high bit is a sign bit) making it longer than the key size, or
which has zero high byte(s), making it shorter than the key size. The
best place to handle this is somewhat uncertain, it's an encoding issue
so it probably shouldn't be visible to the raw crypto routines, but
putting it at the mechanism layer removes the algorithm-independence of
that layer, and putting it at the mid-level sign/key-exchange routine
layer both removes the algorithm-independence and requires duplication of
the code for signatures and encryption. The best place to put it seems to
be at the mechanism layer, since an encoding issue really shouldn't be
visible at the crypto layer, and because it would require duplicating the
handling every time a new PKC implementation is plugged in.
The intent of the size adjustment is to make the data size match the key
length. If it's longer, we try to strip leading zero bytes. If it's
shorter, we pad it with zero bytes to match the key size. The result is
either the data adjusted to match the key size, or CRYPT_ERROR_BADDATA if
this isn't possible */
static int adjustPKCS1Data( BYTE *outData, const BYTE *inData,
const int inLength, const int keySize )
{
int length = inLength;
assert( outData != inData );
/* If it's suspiciously short, don't try and process it */
if( length < 56 )
return( CRYPT_ERROR_BADDATA );
/* If it's of the correct size, exit */
if( length == keySize )
{
memcpy( outData, inData, keySize );
return( CRYPT_OK );
}
/* If it's too long, try and strip leading zero bytes. If it's still too
long, complain */
while( length > keySize && !*inData )
{
length--;
inData++;
}
if( length > keySize )
return( CRYPT_ERROR_BADDATA );
/* We've adjusted the size to account for zero-padding during encoding,
now we have to move the data into a fixed-length format to match the
key size. To do this we copy the payload into the output buffer with
enough leading-zero bytes to bring the total size up to the key size */
memset( outData, 0, keySize );
memcpy( outData + ( keySize - length ), inData, length );
return( CRYPT_OK );
}
/* PGP checksums the PKCS #1 wrapped data (even though this doesn't really
serve any purpose), the following routine calculates this checksum and
either appends it to the data or checks it against the stored value */
static BOOLEAN calculatePGPchecksum( BYTE *dataPtr, const int length,
const BOOLEAN writeChecksum )
{
BYTE *checksumPtr = dataPtr + length;
int checksum = 0, i;
for( i = 0; i < length; i++ )
checksum += dataPtr[ i ];
if( !writeChecksum )
{
int storedChecksum = mgetBWord( checksumPtr );
return( storedChecksum == checksum );
}
mputBWord( checksumPtr, checksum );
return( TRUE );
}
/* PGP includes the session key information alongside the encrypted key so
it's not really possible to import the key into a context in the
conventional sense. Instead, the import code has to create the context
as part of the import process and return it to the caller. This is ugly,
but less ugly than doing a raw import and handling the key directly in
the calling code */
static int extractPGPKey( CRYPT_CONTEXT *iCryptContext, STREAM *stream,
const int length )
{
CRYPT_ALGO cryptAlgo = CRYPT_ALGO_NONE;
MESSAGE_CREATEOBJECT_INFO createInfo;
static const CRYPT_MODE mode = CRYPT_MODE_CFB;
const int pgpAlgoID = sgetc( stream );
int status;
/* Get the session key algorithm. We delay checking the algorithm ID
until after the checksum calculation to reduce the chance of being
used as an oracle */
switch( pgpAlgoID )
{
case PGP_ALGO_3DES:
cryptAlgo = CRYPT_ALGO_3DES;
break;
case PGP_ALGO_BLOWFISH:
cryptAlgo = CRYPT_ALGO_BLOWFISH;
break;
case PGP_ALGO_CAST5:
cryptAlgo = CRYPT_ALGO_CAST;
break;
case PGP_ALGO_IDEA:
cryptAlgo = CRYPT_ALGO_IDEA;
break;
case PGP_ALGO_AES_128:
case PGP_ALGO_AES_192:
case PGP_ALGO_AES_256:
cryptAlgo = CRYPT_ALGO_AES;
}
/* Checksum the session key (this is actually superfluous since any
decryption error will be caught by corrupted PKCS #1 padding with
vastly higher probability than this simple checksum, but we do it
anyway because PGP does it too */
if( !calculatePGPchecksum( sMemBufPtr( stream ), length, FALSE ) )
return( CRYPT_ERROR_BADDATA );
/* Make sure the algorithm ID is valid. We only perform the check at
this point because this returns a different error code than the usual
bad-data, we want to be absolutely sure that the problem really is an
unknown algorithm and not the result of scrambled decrypted data */
if( cryptAlgo == CRYPT_ALGO_NONE )
return( CRYPT_ERROR_NOTAVAIL );
/* Create the context and load the key into it */
setMessageCreateObjectInfo( &createInfo, cryptAlgo );
status = krnlSendMessage( SYSTEM_OBJECT_HANDLE,
RESOURCE_IMESSAGE_DEV_CREATEOBJECT,
&createInfo, OBJECT_TYPE_CONTEXT );
if( cryptStatusError( status ) )
return( status );
krnlSendMessage( createInfo.cryptHandle, RESOURCE_IMESSAGE_SETATTRIBUTE,
( void * ) &mode, CRYPT_CTXINFO_MODE );
*iCryptContext = createInfo.cryptHandle;
return( CRYPT_OK );
}
/****************************************************************************
* *
* Key Derivation Mechanisms *
* *
****************************************************************************/
/* HMAC-based PRF used for PKCS #5 v2 and TLS */
#define HMAC_DATASIZE 64
static void prfInit( HASHFUNCTION hashFunction, void *hashState,
const int hashSize, void *processedKey,
int *processedKeyLength, const void *key,
const int keyLength )
{
BYTE hashBuffer[ HMAC_DATASIZE ], *keyPtr = processedKey;
int i;
/* If the key size is larger than tha SHA data size, reduce it to the
SHA hash size before processing it (yuck. You're required to do this
though) */
if( keyLength > HMAC_DATASIZE )
{
/* Hash the user key down to the hash size and use the hashed form of
the key */
hashFunction( NULL, processedKey, ( void * ) key, keyLength, HASH_ALL );
*processedKeyLength = hashSize;
}
else
{
/* Copy the key to internal storage */
memcpy( processedKey, key, keyLength );
*processedKeyLength = keyLength;
}
/* Perform the start of the inner hash using the zero-padded key XOR'd
with the ipad value */
memset( hashBuffer, HMAC_IPAD, HMAC_DATASIZE );
for( i = 0; i < *processedKeyLength; i++ )
hashBuffer[ i ] ^= *keyPtr++;
hashFunction( hashState, NULL, hashBuffer, HMAC_DATASIZE, HASH_START );
zeroise( hashBuffer, HMAC_DATASIZE );
}
static void prfEnd( HASHFUNCTION hashFunction, void *hashState,
const int hashSize, void *hash,
const void *processedKey, const int processedKeyLength )
{
BYTE hashBuffer[ HMAC_DATASIZE ], digestBuffer[ CRYPT_MAX_HASHSIZE ];
int i;
/* Complete the inner hash and extract the digest */
hashFunction( hashState, digestBuffer, NULL, 0, HASH_END );
/* Perform the outer hash using the zero-padded key XOR'd with the opad
value followed by the digest from the inner hash */
memset( hashBuffer, HMAC_OPAD, HMAC_DATASIZE );
memcpy( hashBuffer, processedKey, processedKeyLength );
for( i = 0; i < processedKeyLength; i++ )
hashBuffer[ i ] ^= HMAC_OPAD;
hashFunction( hashState, NULL, hashBuffer, HMAC_DATASIZE, HASH_START );
zeroise( hashBuffer, HMAC_DATASIZE );
hashFunction( hashState, hash, digestBuffer, hashSize, HASH_END );
zeroise( digestBuffer, CRYPT_MAX_HASHSIZE );
}
/* Perform PKCS #5 v2 derivation */
int derivePKCS5( void *dummy, MECHANISM_DERIVE_INFO *mechanismInfo )
{
HASHFUNCTION hashFunction;
BYTE hashInfo[ MAX_HASHINFO_SIZE ], initialHashInfo[ MAX_HASHINFO_SIZE ];
BYTE processedKey[ HMAC_DATASIZE ], block[ CRYPT_MAX_HASHSIZE ];
BYTE countBuffer[ 4 ];
BYTE *dataOutPtr = mechanismInfo->dataOut;
int hashSize, keyIndex, processedKeyLength, blockCount = 1;
UNUSED( dummy );
/* Set up the block counter buffer. This will never have more than the
last few bits set (8 bits = 5100 bytes of key) so we only change the
last byte */
memset( countBuffer, 0, 4 );
/* Initialise the SHA-1 information with the user key. This is reused
for any future hashing since it's constant */
getHashParameters( mechanismInfo->hashAlgo, &hashFunction, &hashSize );
prfInit( hashFunction, initialHashInfo, hashSize,
processedKey, &processedKeyLength,
mechanismInfo->dataIn, mechanismInfo->dataInLength );
/* Produce enough blocks of output to fill the key */
for( keyIndex = 0; keyIndex < mechanismInfo->dataOutLength;
keyIndex += hashSize, dataOutPtr += hashSize )
{
const int noKeyBytes = \
( mechanismInfo->dataOutLength - keyIndex > hashSize ) ? \
hashSize : mechanismInfo->dataOutLength - keyIndex;
int i;
/* Calculate HMAC( salt || counter ) */
countBuffer[ 3 ] = ( BYTE ) blockCount++;
memcpy( hashInfo, initialHashInfo, MAX_HASHINFO_SIZE );
hashFunction( hashInfo, NULL, mechanismInfo->salt,
mechanismInfo->saltLength, HASH_CONTINUE );
hashFunction( hashInfo, NULL, countBuffer, 4, HASH_CONTINUE );
prfEnd( hashFunction, hashInfo, hashSize, block, processedKey,
processedKeyLength );
memcpy( dataOutPtr, block, noKeyBytes );
/* Calculate HMAC( T1 ) ^ HMAC( T1 ) ^ ... HMAC( Tc ) */
for( i = 0; i < mechanismInfo->iterations - 1; i++ )
{
int j;
/* Generate the PRF output for the current iteration */
memcpy( hashInfo, initialHashInfo, MAX_HASHINFO_SIZE );
hashFunction( hashInfo, NULL, block, hashSize, HASH_CONTINUE );
prfEnd( hashFunction, hashInfo, hashSize, block, processedKey,
processedKeyLength );
/* Xor the new PRF output into the existing PRF output */
for( j = 0; j < noKeyBytes; j++ )
dataOutPtr[ j ] ^= block[ j ];
}
}
zeroise( hashInfo, MAX_HASHINFO_SIZE );
zeroise( initialHashInfo, MAX_HASHINFO_SIZE );
zeroise( processedKey, HMAC_DATASIZE );
zeroise( block, CRYPT_MAX_HASHSIZE );
return( CRYPT_OK );
}
/* Perform SSL key derivation */
int deriveSSL( void *dummy, MECHANISM_DERIVE_INFO *mechanismInfo )
{
HASHFUNCTION md5HashFunction, shaHashFunction;
BYTE hashInfo[ MAX_HASHINFO_SIZE ], hash[ CRYPT_MAX_HASHSIZE ];
BYTE counterData[ 16 ];
int md5HashSize, shaHashSize, counter = 0, keyIndex;
UNUSED( dummy );
getHashParameters( CRYPT_ALGO_MD5, &md5HashFunction, &md5HashSize );
getHashParameters( CRYPT_ALGO_SHA, &shaHashFunction, &shaHashSize );
/* Produce enough blocks of output to fill the key */
for( keyIndex = 0; keyIndex < mechanismInfo->dataOutLength;
keyIndex += md5HashSize )
{
const int noKeyBytes = \
( mechanismInfo->dataOutLength - keyIndex > md5HashSize ) ? \
md5HashSize : mechanismInfo->dataOutLength - keyIndex;
int i;
/* Set up the counter data */
for( i = 0; i <= counter; i++ )
counterData[ i ] = 'A' + counter;
counter++;
/* Calculate SHA1( 'A'/'BB'/'CCC'/... || keyData || salt ) */
shaHashFunction( hashInfo, NULL, counterData, counter, HASH_START );
shaHashFunction( hashInfo, NULL, mechanismInfo->dataIn,
mechanismInfo->dataInLength, HASH_CONTINUE );
shaHashFunction( hashInfo, hash, mechanismInfo->salt,
mechanismInfo->saltLength, HASH_END );
/* Calculate MD5( keyData || SHA1-hash ) */
md5HashFunction( hashInfo, NULL, mechanismInfo->dataIn,
mechanismInfo->dataInLength, HASH_START );
md5HashFunction( hashInfo, hash, hash, shaHashSize, HASH_END );
/* Copy the result to the output */
memcpy( ( BYTE * )( mechanismInfo->dataOut ) + keyIndex, hash, noKeyBytes );
}
zeroise( hashInfo, MAX_HASHINFO_SIZE );
zeroise( hash, CRYPT_MAX_HASHSIZE );
return( CRYPT_OK );
}
/* Perform TLS key derivation (this is the function described as PRF() in the
TLS spec */
int deriveTLS( void *dummy, MECHANISM_DERIVE_INFO *mechanismInfo )
{
HASHFUNCTION md5HashFunction, shaHashFunction;
BYTE md5HashInfo[ MAX_HASHINFO_SIZE ];
BYTE md5InitialHashInfo[ MAX_HASHINFO_SIZE ];
BYTE md5AnHashInfo[ MAX_HASHINFO_SIZE ];
BYTE shaHashInfo[ MAX_HASHINFO_SIZE ];
BYTE shaInitialHashInfo[ MAX_HASHINFO_SIZE ];
BYTE shaAnHashInfo[ MAX_HASHINFO_SIZE ];
BYTE md5ProcessedKey[ HMAC_DATASIZE ], shaProcessedKey[ HMAC_DATASIZE ];
BYTE md5A[ CRYPT_MAX_HASHSIZE ], shaA[ CRYPT_MAX_HASHSIZE ];
BYTE md5Hash[ CRYPT_MAX_HASHSIZE ], shaHash[ CRYPT_MAX_HASHSIZE ];
BYTE *md5DataOutPtr = mechanismInfo->dataOut;
BYTE *shaDataOutPtr = mechanismInfo->dataOut;
const BYTE *dataEndPtr = ( BYTE * ) mechanismInfo->dataOut + \
mechanismInfo->dataOutLength;
const void *s1, *s2;
const int sLen = ( mechanismInfo->dataInLength + 1 ) / 2;
int md5ProcessedKeyLength, shaProcessedKeyLength;
int md5HashSize, shaHashSize, counter = 0, keyIndex;
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -