gladmanContext.cpp [plain text]
#include "gladmanContext.h"
#include "cspdebugging.h"
#include <CommonCrypto/CommonCryptor.h>
GAESContext::GAESContext(AppleCSPSession &session) :
BlockCryptor(session),
mAesKey(NULL),
mInitFlag(false),
mRawKeySize(0),
mWasEncrypting(false)
{
cbcCapable(false);
multiBlockCapable(false);
}
GAESContext::~GAESContext()
{
if(mAesKey) {
CCCryptorFinal(mAesKey,NULL,0,NULL);
CCCryptorRelease(mAesKey);
mAesKey = NULL;
}
deleteKey();
memset(mRawKey, 0, MAX_AES_KEY_BITS / 8);
mInitFlag = false;
}
void GAESContext::deleteKey()
{
mRawKeySize = 0;
}
void GAESContext::init(
const Context &context,
bool encrypting)
{
if(mInitFlag && !opStarted()) {
return;
}
CSSM_SIZE keyLen;
uint8 *keyData = NULL;
bool sameKeySize = false;
symmetricKeyBits(context, session(), CSSM_ALGID_AES,
encrypting ? CSSM_KEYUSE_ENCRYPT : CSSM_KEYUSE_DECRYPT,
keyData, keyLen);
switch(keyLen) {
case kCCKeySizeAES128:
case kCCKeySizeAES192:
case kCCKeySizeAES256:
break;
default:
CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_KEY);
}
if(mRawKeySize == keyLen) {
sameKeySize = true;
}
else {
deleteKey();
}
if(!sameKeySize || (mWasEncrypting != encrypting) ||
memcmp(mRawKey, keyData, mRawKeySize)) {
(void) CCCryptorCreateWithMode(0, kCCModeECB, kCCAlgorithmAES128, ccDefaultPadding, NULL, keyData, keyLen, NULL, 0, 0, 0, &mAesKey);
memmove(mRawKey, keyData, keyLen);
mRawKeySize = (uint32)keyLen;
mWasEncrypting = encrypting;
}
CSSM_ENCRYPT_MODE cssmMode = context.getInt(CSSM_ATTRIBUTE_MODE);
switch (cssmMode) {
case CSSM_ALGMODE_CBCPadIV8:
case CSSM_ALGMODE_CBC_IV8:
{
CssmData *iv = context.get<CssmData>(CSSM_ATTRIBUTE_INIT_VECTOR);
if(iv == NULL) {
CssmError::throwMe(CSSMERR_CSP_MISSING_ATTR_INIT_VECTOR);
}
if(iv->Length != kCCBlockSizeAES128) {
CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_INIT_VECTOR);
}
}
break;
default:
break;
}
setup(GLADMAN_BLOCK_SIZE_BYTES, context);
mInitFlag = true;
}
void GAESContext::encryptBlock(
const void *plainText, size_t plainTextLen,
void *cipherText,
size_t &cipherTextLen, bool final) {
if(cipherTextLen < plainTextLen) {
CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR);
}
(void) CCCryptorEncryptDataBlock(mAesKey, NULL, plainText, plainTextLen, cipherText);
cipherTextLen = plainTextLen;
}
void GAESContext::decryptBlock(
const void *cipherText, size_t cipherTextLen,
void *plainText,
size_t &plainTextLen, bool final) {
if(plainTextLen < cipherTextLen) {
CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR);
}
(void) CCCryptorDecryptDataBlock(mAesKey, NULL, cipherText, cipherTextLen, plainText);
plainTextLen = cipherTextLen;
}