CCCryptorStatus CCCryptWithMode(CCOperation op, CCMode mode, CCAlgorithm alg, CCPadding padding, const void *iv, const void *key, size_t keyLength, const void *tweak, size_t tweakLength, int numRounds, CCModeOptions options, const void *dataIn, size_t dataInLength, void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved) #ifdef CRYPTORWITHMODE { CCCryptorRef cref; CCCryptorStatus retval; size_t moved; if((retval = CCCryptorCreateWithMode(op, mode, alg, padding, iv, key, keyLength, tweak, tweakLength, numRounds, options, &cref)) != kCCSuccess) { return retval; } if((retval = CCCryptorUpdate(cref, dataIn, dataInLength, dataOut, dataOutAvailable, &moved)) != kCCSuccess) { return retval; } dataOut += moved; dataOutAvailable -= moved; *dataOutMoved = moved; if((retval = CCCryptorFinal(cref, dataOut, dataOutAvailable, &moved)) != kCCSuccess) { return retval; } *dataOutMoved += moved; CCCryptorRelease(cref); return kCCSuccess; }
int decryptFinal(HMACCheck hmacCheck) { CCCryptorStatus status; int rv; uint8_t hmacDigest[CC_SHA512_DIGEST_LENGTH]; status = CCCryptorFinal(cryptorRef, compressed, sizeof(compressed), &compressedLen); if (status != kCCSuccess) { printf("cryptor update error\n"); return(-1); } status = CCCryptorRelease(cryptorRef); if (status != kCCSuccess) { printf("cryptor release error\n"); } if (compressedLen) { strm.next_in = compressed; strm.avail_in = (uint)compressedLen; do { strm.next_out = bufOut; strm.avail_out = sizeof(bufOut); rv = inflate(&strm, Z_FINISH); if (rv != Z_OK && rv != Z_STREAM_END && rv != Z_BUF_ERROR) { printf("zlib error\n"); } bufOutLen = sizeof(bufOut) - strm.avail_out; if (bufOutLen) { CCHmacUpdate(&hmacContextPlain, bufOut, bufOutLen); writer(bufOut, bufOutLen); } } while (strm.avail_out == 0); } inflateEnd(&strm); if (hmacCheck == kHmacNoCheck) return(0); /* CHECK */ CCHmacFinal(&hmacContext, &hmacDigest); if (memcmp(header.hmacDigest, hmacDigest, sizeof(hmacDigest))) printf("CRYPT CORRUPT\n"); CCHmacFinal(&hmacContextPlain, &hmacDigest); if (memcmp(header.hmacDigestPlain, hmacDigest, sizeof(hmacDigest))) printf("PLAIN CORRUPT\n"); return(0); }
int encryptFinal(void) { CCCryptorStatus status; int rv; /* finish zlib */ do { strm.next_out = compressed; strm.avail_out = sizeof(compressed); rv = deflate(&strm, Z_FINISH); if (rv != Z_OK && rv != Z_STREAM_END && rv != Z_BUF_ERROR) { printf("zlib error %d\n", rv); } status = CCCryptorUpdate(cryptorRef, compressed, sizeof(compressed) - strm.avail_out, bufOut, sizeof(bufOut), &bufOutLen); if (status != kCCSuccess) { printf("cryptor update error\n"); return(-1); } if (bufOutLen) { CCHmacUpdate(&hmacContext, bufOut, bufOutLen); writer(bufOut, bufOutLen); } } while (strm.avail_out == 0); deflateEnd(&strm); status = CCCryptorFinal(cryptorRef, bufOut, sizeof(bufOut), &bufOutLen); if (status != kCCSuccess) { printf("cryptor update error: %d\n", status); } if (bufOutLen) { CCHmacUpdate(&hmacContext, bufOut, bufOutLen); writer(bufOut, bufOutLen); } status = CCCryptorRelease(cryptorRef); if (status != kCCSuccess) { printf("cryptor release error\n"); } CCHmacFinal(&hmacContext, &header.hmacDigest); CCHmacFinal(&hmacContextPlain, &header.hmacDigestPlain); seeker(0); writer(&header, sizeof(header)); return(0); }
GAESContext::~GAESContext() { if(mAesKey) { CCCryptorFinal(mAesKey,NULL,0,NULL); CCCryptorRelease(mAesKey); mAesKey = NULL; } deleteKey(); memset(mRawKey, 0, MAX_AES_KEY_BITS / 8); mInitFlag = false; }
int32_t AppleCryptoNative_CryptorFinal( CCCryptorRef cryptor, uint8_t* pbOutput, int32_t cbOutput, int32_t* pcbWritten, int32_t* pccStatus) { if (pccStatus == NULL) return -1; *pccStatus = 0; if (pbOutput == NULL || cbOutput < 0 || pcbWritten == NULL) return -1; CCStatus status = CCCryptorFinal(cryptor, pbOutput, (size_t)cbOutput, (size_t*)pcbWritten); *pccStatus = status; return status == kCCSuccess; }
extern "C" int AppleCryptoNative_CryptorFinal( CCCryptorRef cryptor, uint8_t* pbOutput, int32_t cbOutput, int32_t* pcbWritten, int32_t* pccStatus) { if (pccStatus == nullptr) return -1; *pccStatus = 0; if (pbOutput == nullptr || cbOutput < 0 || pcbWritten == nullptr) return -1; CCStatus status = CCCryptorFinal(cryptor, pbOutput, static_cast<size_t>(cbOutput), reinterpret_cast<size_t*>(pcbWritten)); *pccStatus = status; return status == kCCSuccess; }
static void transformAES_CBC(CCOperation operation, const CryptoAlgorithmAesCbcParams& parameters, const CryptoKeyAES& key, const CryptoOperationData& data, std::unique_ptr<PromiseWrapper> promise) { static_assert(sizeof(parameters.iv) == kCCBlockSizeAES128, "Initialization vector size must be the same as algorithm block size"); size_t keyLengthInBytes = key.key().size(); if (keyLengthInBytes != 16 && keyLengthInBytes != 24 && keyLengthInBytes != 32) { promise->reject(nullptr); return; } CCCryptorRef cryptor; #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 CCAlgorithm aesAlgorithm = kCCAlgorithmAES; #else CCAlgorithm aesAlgorithm = kCCAlgorithmAES128; #endif CCCryptorStatus status = CCCryptorCreate(operation, aesAlgorithm, kCCOptionPKCS7Padding, key.key().data(), keyLengthInBytes, parameters.iv.data(), &cryptor); if (status) { promise->reject(nullptr); return; } Vector<uint8_t> result(CCCryptorGetOutputLength(cryptor, data.second, true)); size_t bytesWritten; status = CCCryptorUpdate(cryptor, data.first, data.second, result.data(), result.size(), &bytesWritten); if (status) { promise->reject(nullptr); return; } uint8_t* p = result.data() + bytesWritten; status = CCCryptorFinal(cryptor, p, result.end() - p, &bytesWritten); p += bytesWritten; if (status) { promise->reject(nullptr); return; } ASSERT(p <= result.end()); result.shrink(p - result.begin()); CCCryptorRelease(cryptor); promise->fulfill(result); }
CryptoBuffer CommonCryptoCipher::FinalizeDecryption() { if (m_failure) { AWS_LOGSTREAM_FATAL(CC_LOG_TAG, "Cipher not properly initialized for decryption finalization. Aborting"); return CryptoBuffer(); } CryptoBuffer finalBlock(GetBlockSizeBytes()); size_t writtenSize = static_cast<int>(finalBlock.GetLength()); CCStatus status = CCCryptorFinal(m_cryptoHandle, finalBlock.GetUnderlyingData(), finalBlock.GetLength(), &writtenSize); if (status != kCCSuccess) { m_failure = true; AWS_LOGSTREAM_ERROR(CC_LOG_TAG, "Decryption of buffer failed with status code: " << status); return CryptoBuffer(); } return CryptoBuffer(finalBlock.GetUnderlyingData(), writtenSize); }
static int __aes_process (crypto_aes_t *crypto, CCCryptorRef cryptor, const void *src, unsigned int src_size, void *dst, unsigned int *dst_size) { size_t out_avail; size_t used = 0; uint8_t *outp; size_t moved; pthread_mutex_lock(&(crypto->lock)); outp = (uint8_t *)dst; out_avail = src_size + 16; if (CCCryptorUpdate(cryptor, src, src_size, outp, out_avail, &moved)) { pthread_mutex_unlock(&(crypto->lock)); CCCryptorReset(cryptor, crypto->iv); return(-2); } outp += moved; used += moved; out_avail -= moved; if (CCCryptorFinal(cryptor, outp, out_avail, &moved)) { pthread_mutex_unlock(&(crypto->lock)); CCCryptorReset(cryptor, crypto->iv); return(-3); } used += moved; if (dst_size != NULL) *dst_size = used; CCCryptorReset(cryptor, crypto->iv); pthread_mutex_unlock(&(crypto->lock)); return(0); }
/* * Test harness for CCCryptor with lots of options. */ CCCryptorStatus doCCCrypt( bool forEncrypt, CCAlgorithm encrAlg, bool doCbc, bool doPadding, const void *keyBytes, size_t keyLen, const void *iv, bool randUpdates, bool inPlace, /* !doPadding only */ size_t ctxSize, /* if nonzero, we allocate ctx */ bool askOutSize, const uint8_t *inText, size_t inTextLen, uint8_t **outText, size_t *outTextLen) /* both returned, WE malloc */ { CCCryptorRef cryptor = NULL; CCCryptorStatus crtn; CCOperation op = forEncrypt ? kCCEncrypt : kCCDecrypt; CCOptions options = 0; uint8_t *outBuf = NULL; /* mallocd output buffer */ uint8_t *outp; /* running ptr into outBuf */ const uint8 *inp; /* running ptr into inText */ size_t outLen; /* bytes remaining in outBuf */ size_t toMove; /* bytes remaining in inText */ size_t thisMoveOut; /* output from CCCryptUpdate()/CCCryptFinal() */ size_t outBytes; /* total bytes actually produced in outBuf */ char ctx[CC_MAX_CTX_SIZE]; /* for CCCryptorCreateFromData() */ uint8_t *textMarker = NULL; /* 8 bytes of marker here after expected end of * output */ char *ctxMarker = NULL; /* ditto for caller-provided context */ unsigned dex; size_t askedOutSize; /* from the lib */ size_t thisOutLen; /* dataOutAvailable we use */ if(ctxSize > CC_MAX_CTX_SIZE) { printf("***HEY! Adjust CC_MAX_CTX_SIZE!\n"); exit(1); } if(!doCbc) { options |= kCCOptionECBMode; } if(doPadding) { options |= kCCOptionPKCS7Padding; } /* just hack this one */ outLen = inTextLen; if(forEncrypt) { outLen += MAX_BLOCK_SIZE; } outBuf = (uint8_t *)malloc(outLen + MARKER_LENGTH); memset(outBuf, 0xEE, outLen + MARKER_LENGTH); /* library should not touch this memory */ textMarker = outBuf + outLen; memset(textMarker, MARKER_BYTE, MARKER_LENGTH); /* subsequent errors to errOut: */ if(inPlace) { memmove(outBuf, inText, inTextLen); inp = outBuf; } else { inp = inText; } if(!randUpdates) { /* one shot */ if(askOutSize) { crtn = CCCrypt(op, encrAlg, options, keyBytes, keyLen, iv, inp, inTextLen, outBuf, 0, &askedOutSize); if(crtn != kCCBufferTooSmall) { printf("***Did not get kCCBufferTooSmall as expected\n"); printf(" alg %d inTextLen %lu cbc %d padding %d keyLen %lu\n", (int)encrAlg, (unsigned long)inTextLen, (int)doCbc, (int)doPadding, (unsigned long)keyLen); printCCError("CCCrypt", crtn); crtn = -1; goto errOut; } outLen = askedOutSize; } crtn = CCCrypt(op, encrAlg, options, keyBytes, keyLen, iv, inp, inTextLen, outBuf, outLen, &outLen); if(crtn) { printCCError("CCCrypt", crtn); goto errOut; } *outText = outBuf; *outTextLen = outLen; goto errOut; } /* random multi updates */ if(ctxSize) { size_t ctxSizeCreated; if(askOutSize) { crtn = CCCryptorCreateFromData(op, encrAlg, options, keyBytes, keyLen, iv, ctx, 0 /* ctxSize */, &cryptor, &askedOutSize); if(crtn != kCCBufferTooSmall) { printf("***Did not get kCCBufferTooSmall as expected\n"); printCCError("CCCryptorCreateFromData", crtn); crtn = -1; goto errOut; } ctxSize = askedOutSize; } crtn = CCCryptorCreateFromData(op, encrAlg, options, keyBytes, keyLen, iv, ctx, ctxSize, &cryptor, &ctxSizeCreated); if(crtn) { printCCError("CCCryptorCreateFromData", crtn); return crtn; } ctxMarker = ctx + ctxSizeCreated; memset(ctxMarker, MARKER_BYTE, MARKER_LENGTH); } else { crtn = CCCryptorCreate(op, encrAlg, options, keyBytes, keyLen, iv, &cryptor); if(crtn) { printCCError("CCCryptorCreate", crtn); return crtn; } } toMove = inTextLen; /* total to go */ outp = outBuf; outBytes = 0; /* bytes actually produced in outBuf */ while(toMove) { uint32 thisMoveIn; /* input to CCryptUpdate() */ thisMoveIn = genRand(1, toMove); logSize(("###ptext segment len %lu\n", (unsigned long)thisMoveIn)); if(askOutSize) { thisOutLen = CCCryptorGetOutputLength(cryptor, thisMoveIn, false); } else { thisOutLen = outLen; } crtn = CCCryptorUpdate(cryptor, inp, thisMoveIn, outp, thisOutLen, &thisMoveOut); if(crtn) { printCCError("CCCryptorUpdate", crtn); goto errOut; } inp += thisMoveIn; toMove -= thisMoveIn; outp += thisMoveOut; outLen -= thisMoveOut; outBytes += thisMoveOut; } if(doPadding) { /* Final is not needed if padding is disabled */ if(askOutSize) { thisOutLen = CCCryptorGetOutputLength(cryptor, 0, true); } else { thisOutLen = outLen; } crtn = CCCryptorFinal(cryptor, outp, thisOutLen, &thisMoveOut); } else { thisMoveOut = 0; crtn = kCCSuccess; } if(crtn) { printCCError("CCCryptorFinal", crtn); goto errOut; } outBytes += thisMoveOut; *outText = outBuf; *outTextLen = outBytes; crtn = kCCSuccess; for(dex=0; dex<MARKER_LENGTH; dex++) { if(textMarker[dex] != MARKER_BYTE) { printf("***lib scribbled on our textMarker memory (op=%s)!\n", forEncrypt ? "encrypt" : "decrypt"); crtn = (CCCryptorStatus)-1; } } if(ctxSize) { for(dex=0; dex<MARKER_LENGTH; dex++) { if(ctxMarker[dex] != MARKER_BYTE) { printf("***lib scribbled on our ctxMarker memory (op=%s)!\n", forEncrypt ? "encrypt" : "decrypt"); crtn = (CCCryptorStatus)-1; } } } errOut: if(crtn) { if(outBuf) { free(outBuf); } } if(cryptor) { CCCryptorRelease(cryptor); } return crtn; }
wi_integer_t wi_cipher_decrypt_bytes(wi_cipher_t *cipher, const void *encrypted_buffer, wi_uinteger_t encrypted_length, void *decrypted_buffer) { #ifdef WI_CIPHER_OPENSSL int decrypted_length, padded_length; if(EVP_DecryptUpdate(&cipher->decrypt_ctx, decrypted_buffer, &decrypted_length, encrypted_buffer, encrypted_length) != 1) { wi_error_set_openssl_error(); return -1; } if(EVP_DecryptFinal_ex(&cipher->decrypt_ctx, decrypted_buffer + decrypted_length, &padded_length) != 1) { wi_error_set_openssl_error(); return -1; } if(EVP_DecryptInit_ex(&cipher->decrypt_ctx, NULL, NULL, NULL, NULL) != 1) { wi_error_set_openssl_error(); return -1; } return decrypted_length + padded_length; #endif #ifdef WI_CIPHER_COMMONCRYPTO CCCryptorStatus status; size_t available_length, decrypted_length, padded_length; available_length = wi_cipher_block_size(cipher) + encrypted_length; status = CCCryptorUpdate(cipher->decrypt_ref, encrypted_buffer, encrypted_length, decrypted_buffer, available_length, &decrypted_length); if(status != kCCSuccess) { wi_error_set_commoncrypto_error(status); return -1; } status = CCCryptorFinal(cipher->decrypt_ref, decrypted_buffer + decrypted_length, available_length - decrypted_length, &padded_length); if(status != kCCSuccess) { wi_error_set_commoncrypto_error(status); return -1; } status = CCCryptorReset(cipher->decrypt_ref, cipher->iv ? wi_data_bytes(cipher->iv) : NULL); if(status != kCCSuccess) { wi_error_set_commoncrypto_error(status); return -1; } return decrypted_length + padded_length; #endif }
U8_EXPORT ssize_t u8_cryptic (int do_encrypt,const char *cname, const unsigned char *key,int keylen, const unsigned char *iv,int ivlen, u8_block_reader reader,u8_block_writer writer, void *readstate,void *writestate, u8_context caller) { if (strncasecmp(cname,"rsa",3)==0) { u8_seterr(_("RSA support NYI"),"u8_cryptic/CommonCrypto",u8_strdup(cname)); return -1;} else { CCCryptorRef ctx; CCOptions options=0; ssize_t inlen, outlen, totalin=0, totalout=0, retval=0; unsigned char inbuf[1024], outbuf[1024]; struct U8_CCCIPHER *cipher=get_cipher(cname); if (cipher) { size_t blocksize=cipher->cc_blocksize; ssize_t needivlen=cipher->cc_ivlen; if (!((keylen<=cipher->cc_keymax)&&(keylen>=cipher->cc_keymin))) return u8_reterr(u8_BadCryptoKey, ((caller)?(caller):((u8_context)"u8_cryptic")), u8_mkstring("%d!=[%d,%d](%s)",keylen, cipher->cc_keymin,cipher->cc_keymax, cname)); if ((needivlen)&&(ivlen!=needivlen)) return u8_reterr(u8_BadCryptoIV, ((caller)?(caller):(COMMONCRYPTO_CRYPTIC)), u8_mkstring("%d!=%d(%s)",ivlen,needivlen,cname)); if (needivlen==0) iv=NULL; memset(&ctx,0,sizeof(ctx)); CCCryptorStatus status=CCCryptorCreate (((do_encrypt)? (kCCEncrypt) : (kCCDecrypt)), cipher->cc_algorithm,cipher->cc_opts,key,keylen,iv,&ctx); u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC, " %s cipher=%s, keylen=%d/[%d,%d], ivlen=%d, blocksize=%d\n", ((do_encrypt)?("encrypt"):("decrypt")), cname,keylen,cipher->cc_keymin,cipher->cc_keymax, ivlen,blocksize); while (1) { inlen = reader(inbuf,blocksize,readstate); if (inlen <= 0) { u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC, "Finished %s(%s) with %ld in, %ld out", ((do_encrypt)?("encrypt"):("decrypt")),cname, totalin,totalout); break;} if ((status=CCCryptorUpdate(ctx,inbuf,inlen,outbuf,1024,&outlen)) !=kCCSuccess) { CCCryptorRelease(ctx); return u8_reterr(u8_InternalCryptoError, ((caller)?(caller):((u8_context)"u8_cryptic")), NULL);} else { u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC, "%s(%s) consumed %d/%ld bytes, emitted %d/%ld bytes" " in=<%v>\n out=<%v>", ((do_encrypt)?("encrypt"):("decrypt")),cname, inlen,totalin,outlen,totalout+outlen, inbuf,inlen,outbuf,outlen); writer(outbuf,outlen,writestate); totalout=totalout+outlen;}} if ((status=CCCryptorFinal(ctx,outbuf,1024,&outlen))!=kCCSuccess) { CCCryptorRelease(ctx); return u8_reterr(u8_InternalCryptoError, ((caller)?(caller):((u8_context)"u8_cryptic")), NULL);} else { writer(outbuf,outlen,writestate); u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC, "%s(%s) done after consuming %ld/%ld bytes, emitting %ld/%ld bytes" "\n final out=<%v>", ((do_encrypt)?("encrypt"):("decrypt")),cname, inlen,totalin,outlen,totalout+outlen, outbuf,outlen); CCCryptorRelease(ctx); totalout=totalout+outlen; return totalout;}} else return u8_reterr("Unknown cipher", ((caller)?(caller):((u8_context)"u8_cryptic")), u8_strdup(cname)); } }
int Crypto::CipherFinal(Cipher c, char *out, int outlen) { size_t wrote = 0; if (CCCryptorFinal(FromVoid<CCCipher*>(c)->ctx, out, outlen, &wrote) != kCCSuccess) return -1; return wrote; }