#include "castContext.h"
CastContext::CastContext(AppleCSPSession &session) :
BlockCryptor(session),
mCastKey(NULL),
mInitFlag(false),
mRawKeySize(0)
{
}
CastContext::~CastContext()
{
deleteKey();
}
void CastContext::deleteKey()
{
if (mCastKey != NULL) {
CCCryptorRelease(mCastKey);
}
mCastKey = NULL;
mInitFlag = false;
}
void CastContext::init(
const Context &context,
bool encrypting)
{
if(mInitFlag && !opStarted()) {
return;
}
CSSM_SIZE keyLen;
uint8 *keyData = NULL;
bool sameKeySize = false;
symmetricKeyBits(context, session(), CSSM_ALGID_CAST,
encrypting ? CSSM_KEYUSE_ENCRYPT : CSSM_KEYUSE_DECRYPT,
keyData, keyLen);
if((keyLen < kCCKeySizeMinCAST) || (keyLen > kCCKeySizeMaxCAST)) {
CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_KEY);
}
if(mRawKeySize == keyLen) {
sameKeySize = true;
}
else {
deleteKey();
}
if(!sameKeySize || memcmp(mRawKey, keyData, mRawKeySize)) {
(void) CCCryptorCreateWithMode(0, kCCModeECB, kCCAlgorithmCAST, ccDefaultPadding, NULL, keyData, keyLen, NULL, 0, 0, 0, &mCastKey);
memmove(mRawKey, keyData, keyLen);
mRawKeySize = (uint32)keyLen;
}
setup(kCCBlockSizeCAST, context);
mInitFlag = true;
}
void CastContext::encryptBlock(
const void *plainText, size_t plainTextLen,
void *cipherText,
size_t &cipherTextLen, bool final) {
if(plainTextLen != kCCBlockSizeCAST) {
CssmError::throwMe(CSSMERR_CSP_INPUT_LENGTH_ERROR);
}
if(cipherTextLen < kCCBlockSizeCAST) {
CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR);
}
(void) CCCryptorEncryptDataBlock(mCastKey, NULL, plainText, kCCBlockSizeCAST, cipherText);
cipherTextLen = kCCBlockSizeCAST;
}
void CastContext::decryptBlock(
const void *cipherText, size_t cipherTextLen,
void *plainText,
size_t &plainTextLen, bool final) {
if(plainTextLen < kCCBlockSizeCAST) {
CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR);
}
(void) CCCryptorDecryptDataBlock(mCastKey, NULL, cipherText, kCCBlockSizeCAST, plainText);
plainTextLen = kCCBlockSizeCAST;
}