static BUF_MEM * cipher(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc, const BUF_MEM * in) { BUF_MEM * out = NULL; EVP_CIPHER_CTX * tmp_ctx = NULL; int i; unsigned long flags; check(in, "Invalid arguments"); if (ctx) tmp_ctx = ctx; else { tmp_ctx = EVP_CIPHER_CTX_new(); if (!tmp_ctx) goto err; EVP_CIPHER_CTX_init(tmp_ctx); if (!EVP_CipherInit_ex(tmp_ctx, type, impl, key, iv, enc)) goto err; } flags = EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(tmp_ctx)); if (flags & EVP_CIPH_NO_PADDING) { i = in->length; check((in->length % EVP_CIPHER_block_size(type) == 0), "Data is not of blocklength"); } else i = in->length + EVP_CIPHER_block_size(type); out = BUF_MEM_create(i); if (!out) goto err; if (!EVP_CipherUpdate(tmp_ctx, (unsigned char *) out->data, &i, (unsigned char *) in->data, in->length)) goto err; out->length = i; if (!EVP_CipherFinal_ex(tmp_ctx, (unsigned char *) (out->data + out->length), &i)) goto err; if (!(flags & EVP_CIPH_NO_PADDING)) out->length += i; if (!ctx) EVP_CIPHER_CTX_free(tmp_ctx); return out; err: if (out) BUF_MEM_free(out); if (!ctx && tmp_ctx) EVP_CIPHER_CTX_free(tmp_ctx); return NULL; }
BUF_MEM * compute_authentication_token(int protocol, const KA_CTX *ka_ctx, EVP_PKEY *opp_key, BN_CTX *bn_ctx, enum eac_tr_version tr_version) { BUF_MEM *asn1 = NULL, *out = NULL, *pad =NULL; check(ka_ctx, "Invalid arguments"); asn1 = asn1_pubkey(protocol, opp_key, bn_ctx, tr_version); /* ISO 9797-1 algorithm 3 retail MAC now needs extra padding (padding method 2) */ if (EVP_CIPHER_nid(ka_ctx->cipher) == NID_des_ede_cbc) { pad = add_iso_pad(asn1, EVP_CIPHER_block_size(ka_ctx->cipher)); if (!pad) goto err; out = authenticate(ka_ctx, pad); } else { out = authenticate(ka_ctx, asn1); } err: if (asn1) BUF_MEM_free(asn1); if (pad) BUF_MEM_free(pad); return out; }
int main(int argc, char **argv) { int i; char *names[] = { "sms4-ecb", "sms4-cbc", "sms4-cfb", "sms4-ofb", "sms4-ctr", }; const EVP_CIPHER *cipher; OpenSSL_add_all_ciphers(); printf("%s new ciphers:\n\n", OPENSSL_VERSION_TEXT); for (i = 0; i < sizeof(names)/sizeof(names[i]); i++) { if (!(cipher = EVP_get_cipherbyname(names[i]))) { fprintf(stderr, "cipher \"%s\" is not supported\n", names[i]); continue; } printf(" cipher nid : %d\n", EVP_CIPHER_nid(cipher)); printf(" cipher name : %s\n", EVP_CIPHER_name(cipher)); printf(" block size : %d\n", EVP_CIPHER_block_size(cipher)); printf(" key length : %d\n", EVP_CIPHER_key_length(cipher)); printf(" iv length : %d\n", EVP_CIPHER_iv_length(cipher)); printf(" flags : 0x%016lx\n", EVP_CIPHER_flags(cipher)); printf("\n"); } return 0; }
int encode_ssc(const BIGNUM *ssc, const KA_CTX *ctx, unsigned char **encoded) { unsigned char *p; size_t en_len, bn_len; if (!ctx || !encoded) { log_err("Invalid arguments"); return -1; } en_len = EVP_CIPHER_block_size(ctx->cipher); p = OPENSSL_realloc(*encoded, en_len); if (!p) { log_err("Realloc failure"); return -1; } *encoded = p; bn_len = BN_num_bytes(ssc); if (bn_len <= en_len) { memset(*encoded, 0, en_len - bn_len); BN_bn2bin(ssc, *encoded + en_len - bn_len); } else { p = OPENSSL_malloc(bn_len); if (!p) return -1; BN_bn2bin(ssc, p); /* Flawfinder: ignore */ memcpy(*encoded, p + bn_len - en_len, en_len); OPENSSL_free(p); } return en_len; }
wi_boolean_t wi_cipher_decrypt_bytes(wi_cipher_t *cipher, const void *encrypted_buffer, wi_uinteger_t encrypted_length, void **out_buffer, wi_uinteger_t *out_length) { void *decrypted_buffer; int decrypted_length, padded_length; decrypted_buffer = wi_malloc(encrypted_length + EVP_CIPHER_block_size(cipher->cipher)); if(EVP_DecryptUpdate(&cipher->decrypt_ctx, decrypted_buffer, &decrypted_length, encrypted_buffer, encrypted_length) != 1) { wi_error_set_openssl_error(); wi_free(decrypted_buffer); return false; } if(EVP_DecryptFinal_ex(&cipher->decrypt_ctx, decrypted_buffer + decrypted_length, &padded_length) != 1) { wi_error_set_openssl_error(); wi_free(decrypted_buffer); return false; } if(EVP_DecryptInit_ex(&cipher->decrypt_ctx, NULL, NULL, NULL, NULL) != 1) { wi_error_set_openssl_error(); wi_free(decrypted_buffer); return false; } *out_buffer = decrypted_buffer; *out_length = decrypted_length + padded_length; return true; }
pubnub_bymebl_t pbaes256_decrypt_alloc(pubnub_bymebl_t data, uint8_t const* key, uint8_t const* iv) { int decrypt_result; EVP_CIPHER_CTX *aes256; pubnub_bymebl_t result; result.size = data.size + EVP_CIPHER_block_size(EVP_aes_256_cbc()) + 1; result.ptr = (uint8_t*)malloc(result.size); if (NULL == result.ptr) { return result; } aes256 = EVP_CIPHER_CTX_new(); if (NULL == aes256) { PUBNUB_LOG_ERROR("Failed to allocate AES-256 decryption context\n"); free(result.ptr); result.ptr = NULL; return result;; } decrypt_result = do_decrypt(aes256, data, key, iv, &result); EVP_CIPHER_CTX_free(aes256); if (decrypt_result != 0) { PUBNUB_LOG_ERROR("Failed AES-256 decryption\n"); free(result.ptr); result.ptr = NULL; } return result; }
pubnub_bymebl_t pbaes256_encrypt_alloc(pubnub_bymebl_t msg, uint8_t const* key, uint8_t const* iv) { int encrypt_result; pubnub_bymebl_t result = { NULL, 0 }; EVP_CIPHER_CTX* aes256 = EVP_CIPHER_CTX_new(); if (NULL == aes256) { PUBNUB_LOG_ERROR("Failed to allocate AES-256 encryption context\n"); return result; } result.ptr = (uint8_t*)malloc(msg.size + EVP_CIPHER_block_size(EVP_aes_256_cbc())); if (NULL == result.ptr) { EVP_CIPHER_CTX_free(aes256); PUBNUB_LOG_ERROR("Failed to allocate memory for AES-256 encryption\n"); return result; } encrypt_result = do_encrypt(aes256, msg, key, iv, &result); if (-1 == encrypt_result) { free(result.ptr); result.ptr = NULL; } EVP_CIPHER_CTX_free(aes256); return result; }
RTDECL(uint32_t) RTCrCipherGetBlockSize(RTCRCIPHER hCipher) { RTCRCIPHERINT *pThis = hCipher; AssertPtrReturn(pThis, 0); AssertReturn(pThis->u32Magic == RTCRCIPHERINT_MAGIC, 0); return EVP_CIPHER_block_size(pThis->pCipher); }
static struct json_object * pubnub_decrypt(const char *cipher_key, const char *b64_str) { int b64_len = strlen(b64_str); unsigned char iv[] = "0123456789012345"; /* Pre-process (hash) encryption key */ unsigned char cipher_hash[33]; pubnub_sha256_cipher_key(cipher_key, cipher_hash); /* Convert base64 encrypted text to raw data. */ BIO *b64f = BIO_new(BIO_f_base64()); BIO_set_flags(b64f, BIO_FLAGS_BASE64_NO_NL); BIO *bmem = BIO_new_mem_buf((unsigned char *) b64_str, b64_len); BIO *b64 = BIO_push(b64f, bmem); /* b64_len is fine upper bound for raw data length... */ unsigned char *cipher_data = (unsigned char*)malloc(b64_len); int cipher_len = BIO_read(b64, cipher_data, b64_len); BIO_free_all(b64); /* Decrypt the message */ EVP_CIPHER_CTX aes256; EVP_CIPHER_CTX_init(&aes256); if (!EVP_DecryptInit_ex(&aes256, EVP_aes_256_cbc(), NULL, cipher_hash, iv)) { DBGMSG("DecryptInit error\n"); return NULL; } char *message_str = (char*)malloc(cipher_len + EVP_CIPHER_block_size(EVP_aes_256_cbc()) + 1); int message_len = 0; if (!EVP_DecryptUpdate(&aes256, (unsigned char *) message_str, &message_len, cipher_data, cipher_len)) { DBGMSG("DecryptUpdate error\n"); return NULL; } int message_flen; if (!EVP_DecryptFinal_ex(&aes256, (unsigned char *) message_str + message_len, &message_flen)) { DBGMSG("DecryptFinal error\n"); return NULL; } message_len += message_flen; EVP_CIPHER_CTX_cleanup(&aes256); free(cipher_data); /* Conjure up JSON object */ message_str[message_len] = 0; DBGMSG("dec inp: <%s>\n", message_str); struct json_object *message = json_tokener_parse(message_str); free(message_str); return message; }
bool Crypto_t::symmetricCipher(const std::vector<unsigned char>& in_buffer, int nid, const std::string& key, const std::string& iv, bool encode, std::vector<unsigned char>& buffer) { // load all cipher modules OpenSSL_add_all_ciphers(); // Select the specific cipher module const EVP_CIPHER* cipher = EVP_get_cipherbynid(nid); if (!cipher) return false; // Each cipher has its own taste for the key and IV. So we need to check if the input key and IV is appropriate // for the specific cipher module if (key.size() < static_cast<size_t>(EVP_CIPHER_key_length(cipher)) || iv.size() < static_cast<size_t>(EVP_CIPHER_iv_length(cipher))) { return false; } EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); EVP_CipherInit_ex(&ctx, cipher, NULL, (const unsigned char*)key.c_str(), (const unsigned char*)iv.c_str(), encode); size_t block_size = EVP_CIPHER_block_size(cipher); unsigned char* encrypt_buffer = (unsigned char*) malloc(block_size + in_buffer.size()); // Read the raw buffer and convert to encrypt one. And then collect to the output buffer int out_count = 0; buffer.clear(); bool fail = false; while (true) { if (!EVP_CipherUpdate(&ctx, encrypt_buffer, &out_count, &in_buffer[0], in_buffer.size())) { fail = true; break; } for (int i = 0; i < out_count; i++) buffer.push_back(encrypt_buffer[i]); // handling the last block unsigned char* block = encrypt_buffer + out_count; if (!EVP_CipherFinal_ex(&ctx, block, &out_count)) { fail = true; break; } for (int i = 0; i < out_count; i++) buffer.push_back(block[i]); break; } // free resource free(encrypt_buffer); EVP_CIPHER_CTX_cleanup(&ctx); return (fail == true) ? (false) : (true); }
int cipher_kt_block_size(const EVP_CIPHER *cipher) { /* * OpenSSL reports OFB/CFB/GCM cipher block sizes as '1 byte'. To work * around that, try to replace the mode with 'CBC' and return the block size * reported for that cipher, if possible. If that doesn't work, just return * the value reported by OpenSSL. */ char *name = NULL; char *mode_str = NULL; const char *orig_name = NULL; const EVP_CIPHER *cbc_cipher = NULL; int block_size = EVP_CIPHER_block_size(cipher); orig_name = cipher_kt_name(cipher); if (!orig_name) { goto cleanup; } name = string_alloc(translate_cipher_name_to_openvpn(orig_name), NULL); mode_str = strrchr(name, '-'); if (!mode_str || strlen(mode_str) < 4) { goto cleanup; } strcpy(mode_str, "-CBC"); cbc_cipher = EVP_get_cipherbyname(translate_cipher_name_from_openvpn(name)); if (cbc_cipher) { block_size = EVP_CIPHER_block_size(cbc_cipher); } cleanup: free(name); return block_size; }
static void sl_decrypt (void){ /* input types */ char *ctype; unsigned char *outbuf, *iiv, *ikey, *idata; SLang_BString_Type *iv, *key, *data; /* internal types */ EVP_CIPHER_CTX ctx; const EVP_CIPHER *cipher; int outlen, tmplen, dlen, i; /* output types */ SLang_BString_Type *output; if (SLang_Num_Function_Args != 4 || SLang_pop_slstring(&ctype) == -1 ){ return; } cipher = EVP_get_cipherbyname(ctype); if (!cipher){ SLang_verror(SL_UNDEFINED_NAME,"could not find cipher %s",ctype); return; } if (SLang_pop_bstring(&iv) == -1 || SLang_pop_bstring(&key) == -1 || SLang_pop_bstring(&data) == -1 ){ return; } iiv = SLbstring_get_pointer (iv,&i); ikey = SLbstring_get_pointer (key,&i); idata = SLbstring_get_pointer (data,&dlen); outbuf = (char*)malloc(dlen+EVP_CIPHER_block_size(cipher)); EVP_CIPHER_CTX_init(&ctx); EVP_DecryptInit_ex(&ctx, cipher, NULL, ikey, iiv); if (!EVP_DecryptUpdate(&ctx, outbuf, &outlen, idata, dlen)){ return; /*emit an error here*/ } if (!EVP_DecryptFinal(&ctx, outbuf + outlen, &tmplen)){ return; /*emit an error here*/ } outlen+=tmplen; output = SLbstring_create (outbuf, outlen); SLang_push_bstring(output); SLbstring_free(output); SLbstring_free(data); SLbstring_free(key); SLbstring_free(iv); free(outbuf); }
/* evp_cipher method */ static LUA_FUNCTION(openssl_cipher_info) { EVP_CIPHER *cipher = CHECK_OBJECT(1, EVP_CIPHER, "openssl.evp_cipher"); lua_newtable(L); AUXILIAR_SET(L, -1, "name", EVP_CIPHER_name(cipher), string); AUXILIAR_SET(L, -1, "block_size", EVP_CIPHER_block_size(cipher), integer); AUXILIAR_SET(L, -1, "key_length", EVP_CIPHER_key_length(cipher), integer); AUXILIAR_SET(L, -1, "iv_length", EVP_CIPHER_iv_length(cipher), integer); AUXILIAR_SET(L, -1, "flags", EVP_CIPHER_flags(cipher), integer); AUXILIAR_SET(L, -1, "mode", EVP_CIPHER_mode(cipher), integer); return 1; }
unsigned char* ship_encrypt(const char *algo, unsigned char *key, unsigned char *iv, unsigned char *text, int *clen) { unsigned char *cipher = NULL; unsigned char *c = NULL; unsigned char out[1024 + EVP_MAX_BLOCK_LENGTH]; unsigned char in[1024]; int olen = 0, ilen = 0, bsize = 0, i = 0, tlen = 0, csize = 0; EVP_CIPHER_CTX ctx; const EVP_CIPHER *ci; EVP_CIPHER_CTX_init (&ctx); ci = EVP_get_cipherbyname(algo); if (!ci) { LOG_ERROR("unknown cipher algorithm %s\n", algo); goto err; } ASSERT_TRUE(bsize = EVP_CIPHER_block_size(ci), err); tlen = strlen((char*)text); csize = ((tlen/bsize + 1) * bsize) + 1; ASSERT_TRUE(cipher = mallocz(csize * sizeof(unsigned char)), err); ASSERT_TRUE(EVP_EncryptInit_ex(&ctx, ci, NULL, key, iv), err); c = cipher; *clen = 0; while (i < tlen) { /* get part of text */ ilen = (i+1024<tlen)?1024:tlen-i; memcpy (in, text, ilen); text += ilen; i += ilen; /* copy encrypt-part */ ASSERT_TRUE(EVP_EncryptUpdate (&ctx, out, &olen, in, ilen), err); memcpy (c, out, olen); c += olen; /* increment cipher len */ *clen += olen; } ASSERT_TRUE(EVP_EncryptFinal_ex(&ctx, out, &olen), err); memcpy (c, out, olen); *clen += olen; EVP_CIPHER_CTX_cleanup(&ctx); return cipher; err: freez(cipher); return NULL; }
static void get_EVP_CIPHER_once_cb(void *d) { struct once_init_cipher_ctx *arg = d; const EVP_CIPHER *ossl_evp; hc_EVP_CIPHER *hc_evp; hc_evp = arg->hc_memoize; /* * We lookup EVP_CIPHER *s by NID so that we don't fail to find a * symbol such as EVP_aes...() when libcrypto changes after build * time (e.g., updates, LD_LIBRARY_PATH/LD_PRELOAD). */ ossl_evp = EVP_get_cipherbynid(arg->nid); if (ossl_evp == NULL) { (void) memset(hc_evp, 0, sizeof(*hc_evp)); #if HCRYPTO_FALLBACK *arg->hc_memoizep = arg->fallback; #endif return; } /* Build the hc_EVP_CIPHER */ hc_evp->nid = EVP_CIPHER_nid(ossl_evp); /* We would an hcrypto NIDs if we had them */ hc_evp->block_size = EVP_CIPHER_block_size(ossl_evp); hc_evp->key_len = EVP_CIPHER_key_length(ossl_evp); hc_evp->iv_len = EVP_CIPHER_iv_length(ossl_evp); /* * We force hc_EVP_CipherInit_ex to always call our init() function, * otherwise we don't get a chance to call EVP_CipherInit_ex() * correctly. */ hc_evp->flags = hc_EVP_CIPH_ALWAYS_CALL_INIT | arg->flags; /* Our cipher context */ hc_evp->ctx_size = sizeof(struct ossl_cipher_ctx); /* Our wrappers */ hc_evp->init = cipher_ctx_init; hc_evp->do_cipher = cipher_do_cipher; hc_evp->cleanup = cipher_cleanup; hc_evp->set_asn1_parameters = NULL; hc_evp->get_asn1_parameters = NULL; hc_evp->ctrl = cipher_ctrl; /* Our link to the OpenSSL EVP_CIPHER */ hc_evp->app_data = (void *)ossl_evp; /* Finally, set the static hc_EVP_CIPHER * to the one we just built */ *arg->hc_memoizep = hc_evp; }
int dtls1_enc(SSL *s, int send) { SSL3_RECORD *rec; EVP_CIPHER_CTX *ds; unsigned long l; int bs,i,ii,j,k,n=0; const EVP_CIPHER *enc; if (send) { if (EVP_MD_CTX_md(s->write_hash)) { n=EVP_MD_CTX_size(s->write_hash); if (n < 0) return -1; } ds=s->enc_write_ctx; rec= &(s->s3->wrec); if (s->enc_write_ctx == NULL) enc=NULL; else { enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx); if ( rec->data != rec->input) /* we can't write into the input stream */ #ifndef OPENSSL_SYS_WINDOWS TINYCLR_SSL_PRINTF("%s:%d: rec->data != rec->input\n", __FILE__, __LINE__); #else TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR, "%s:%d: rec->data != rec->input\n", __FILE__, __LINE__); #endif else if ( EVP_CIPHER_block_size(ds->cipher) > 1) { if (RAND_bytes(rec->input, EVP_CIPHER_block_size(ds->cipher)) <= 0) return -1; } } }
wi_uinteger_t wi_cipher_block_size(wi_cipher_t *cipher) { #ifdef WI_CIPHER_OPENSSL return EVP_CIPHER_block_size(cipher->cipher); #endif #ifdef WI_CIPHER_COMMONCRYPTO switch(cipher->type) { case WI_CIPHER_AES128: return kCCBlockSizeAES128; case WI_CIPHER_3DES192: return kCCBlockSize3DES; default: return 0; } #endif }
/** Get required size for an encrypted buffer of the given plain text length. * @param plain_length length of the plain text buffer to encrypt * @return length of encrypted buffer required */ size_t BufferEncryptor::encrypted_buffer_size(size_t plain_length) { #ifdef HAVE_LIBCRYPTO const EVP_CIPHER *evp_cipher = cipher_by_id(cipher_id_); const size_t iv_size = EVP_CIPHER_iv_length(evp_cipher); size_t block_size = EVP_CIPHER_block_size(evp_cipher); return (((plain_length / block_size) + 1) * block_size) + iv_size; #else throw std::runtime_error("Encryption not supported"); #endif }
unsigned char* ship_decrypt(const char *algo, unsigned char *key, unsigned char *iv, unsigned char *cipher, int clen) { unsigned char *decipher = NULL; unsigned char *d = NULL; unsigned char out[1024 + EVP_MAX_BLOCK_LENGTH]; unsigned char in[1024]; int olen = 0, ilen = 0, dlen = 0, bsize= 0, i = 0; EVP_CIPHER_CTX ctx; const EVP_CIPHER *ci; EVP_CIPHER_CTX_init (&ctx); ci = EVP_get_cipherbyname(algo); if(!ci) { LOG_ERROR("unknown cipher algorithm %s\n", algo); goto err; } ASSERT_TRUE(bsize = EVP_CIPHER_block_size(ci), err); dlen = clen + bsize + 1; ASSERT_TRUE(decipher = mallocz( dlen * sizeof(unsigned char)), err); /* d points to decipher */ d = decipher; ASSERT_TRUE(EVP_DecryptInit_ex (&ctx, ci, NULL, key, iv), err); while (i < clen) { /* get part of cipher */ ilen = (i+1024<clen)?1024:clen-i; memcpy (in, cipher, ilen); cipher += ilen; i += ilen; /* copy descrypt-part */ ASSERT_TRUE(EVP_DecryptUpdate (&ctx, out, &olen, in, ilen), err); memcpy (d, out, olen); d += olen; } ASSERT_TRUE(EVP_DecryptFinal_ex(&ctx, out, &olen), err); memcpy (d, out, olen); EVP_CIPHER_CTX_cleanup(&ctx); return decipher; err: freez(decipher); return NULL; }
static uint64_t byte_budget(const EVP_CIPHER *cipher) { /* Hopefully some failsafe way to calculate the maximum amount of bytes to send/receive with a given cipher before we might run into birthday paradox attacks. Because we might use different modes, the block size of the mode might be 1 byte. In that case, use the IV length. Ensure the whole thing is limited to what can be represented with a 64 bits integer. */ int ivlen = EVP_CIPHER_iv_length(cipher); int blklen = EVP_CIPHER_block_size(cipher); int len = blklen > 1 ? blklen : ivlen > 1 ? ivlen : 8; int bits = len * 4 - 1; return bits < 64 ? UINT64_C(1) << bits : UINT64_MAX; }
/* * Function: aesIsFast * Purpose: Test if AES performance is sufficient to require encryption * Parameters: none * Returns: boolean: (true) if AES performance is acceptable, (false) otherwise * Exceptions: InvalidKeyException if EVP_DecryptInit fails, OutOfMemoryError * if memory allocation fails. */ static jboolean android_security_cts_EncryptionTest_aesIsFast(JNIEnv *env, jobject) { EVP_CIPHER_CTX ctx; uint8_t *buf; uint8_t key[EVP_CIPHER_key_length(TEST_EVP_CIPHER)]; uint8_t iv[EVP_CIPHER_iv_length(TEST_EVP_CIPHER)]; memset(key, 0x42, sizeof(key)); memset(iv, 0x11, sizeof(iv)); EVP_CIPHER_CTX_init(&ctx); if (!EVP_DecryptInit(&ctx, TEST_EVP_CIPHER, key, iv)) { jniThrowException(env, "java/security/InvalidKeyException", "EVP_DecryptInit failed"); return false; } buf = new (std::nothrow) uint8_t[TEST_BUFSIZE + EVP_CIPHER_block_size(TEST_EVP_CIPHER)]; if (!buf) { jniThrowException(env, "java/lang/OutOfMemoryError", "Failed to allocate test buffer"); return false; } memset(buf, 0xF0, TEST_BUFSIZE); int len; uint64_t t = ns(); for (int i = 0; i < TEST_ITERATIONS; ++i) { EVP_DecryptUpdate(&ctx, buf, &len, buf, TEST_BUFSIZE); } t = ns() - t; delete[] buf; unsigned long ms = (unsigned long)(t / 1000000); double speed = (double)(TEST_ITERATIONS * TEST_BUFSIZE / (1024 * 1024)) * 1000.0 / ms; ALOGE("EncryptionTest::aesIsFast: %u iterations in %lu ms (%.01lf MiB/s) " "(threshold %u ms)", TEST_ITERATIONS, ms, speed, TEST_THRESHOLD); return ms < TEST_THRESHOLD; }
CK_RV PKCS11_Encryption_OpenSSL::Decrypt(Cryptoki_Session_Context* pSessionCtx, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { OPENSSL_HEADER(); if(pData == NULL) { OpenSSLEncryptData *pDecr; int blockSize; int mod; if(pSessionCtx == NULL || pSessionCtx->DecryptionCtx == NULL) return CKR_SESSION_CLOSED; pDecr = (OpenSSLEncryptData*)pSessionCtx->DecryptionCtx; if(pDecr->IsSymmetric) { blockSize = EVP_CIPHER_block_size(pDecr->SymmetricCtx.cipher); } else { blockSize = EVP_PKEY_size((EVP_PKEY*)pDecr->Key->key); } mod = ulEncryptedDataLen % blockSize; if(0 != mod) { *pulDataLen = ulEncryptedDataLen + (blockSize - mod); } else { *pulDataLen = ulEncryptedDataLen + blockSize; } return CKR_OK; } CK_ULONG tmp = *pulDataLen; OPENSSL_CHECK_CK_RESULT(PKCS11_Encryption_OpenSSL::DecryptUpdate(pSessionCtx, pEncryptedData, ulEncryptedDataLen, pData, pulDataLen)); tmp -= *pulDataLen; OPENSSL_CHECK_CK_RESULT(PKCS11_Encryption_OpenSSL::DecryptFinal(pSessionCtx, &pData[*pulDataLen], &tmp)); *pulDataLen += tmp; OPENSSL_NOCLEANUP(); }
unsigned char* sym_crypt(void* buf, int buf_size, unsigned char* key, int* cipher_len){ EVP_CIPHER_CTX* ctx; FILE* fd; unsigned char* ciphertext; int res, msg_len, n; int outlen, outlen_tot; int ct_bufsize; int block_size = EVP_CIPHER_block_size(SYM_CIPHER); //printf("block_size: %i\n", block_size); if(buf == NULL || key == NULL) return NULL; ctx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX)); EVP_CIPHER_CTX_init(ctx); EVP_EncryptInit(ctx, SYM_CIPHER, key, NULL); //Cosa fare con l' IV? /* Buffer allocation for the ciphertext */ msg_len = buf_size; ct_bufsize = msg_len + block_size; ciphertext = (unsigned char*)malloc(ct_bufsize); outlen = 0; outlen_tot = 0;//dimensione testo output(ciphertext) n=0;//dimensione testo input (plaintext) while(n/block_size < msg_len/block_size){//block size serve nel caso in cui msg_len < block_size allora non devo entrare nel ciclo EVP_EncryptUpdate(ctx, ciphertext + outlen_tot, &outlen, (unsigned char*)buf + n,block_size); outlen_tot += outlen; n += block_size; } EVP_EncryptUpdate(ctx, ciphertext + outlen_tot, &outlen, (unsigned char*)buf + n,msg_len % block_size);// cifro i byte restanti(quelli non multipli di block size outlen_tot += outlen; n += msg_len % block_size; EVP_EncryptFinal(ctx, ciphertext + outlen_tot, &outlen); outlen_tot += outlen; EVP_CIPHER_CTX_cleanup(ctx); free(ctx); *cipher_len = outlen_tot; return ciphertext; }
/* * This function encrypts a string before calling send_msg. * It also append the given IV for the ecnryption mode. * It returns the length of the cipher text (iv is not considered), -1 on error. * Errno is set appropriately */ int encrypt_msg(int sk, char format, unsigned char* plain, unsigned int plain_len, unsigned char* shared_secret) { EVP_CIPHER_CTX* ctx; unsigned char* iv; unsigned int iv_len = EVP_MAX_IV_LENGTH; unsigned char* outbuf = NULL; int outlen, outtot = 0; ctx = (EVP_CIPHER_CTX*)calloc(1, sizeof(EVP_CIPHER_CTX)); EVP_CIPHER_CTX_init(ctx); iv = (unsigned char*)calloc(1, iv_len); RAND_bytes(iv, iv_len); if (EVP_EncryptInit(ctx, EVP_aes_256_cbc(), shared_secret, iv) == 0) { goto fail; } outbuf = (unsigned char*)calloc(1, plain_len + EVP_CIPHER_block_size(EVP_aes_256_cbc()) + iv_len); if (EVP_EncryptUpdate(ctx, outbuf + iv_len, &outlen, plain, plain_len) == 0) { goto fail; } outtot += outlen; if (EVP_EncryptFinal(ctx, outbuf + iv_len + outtot, &outlen) == 0) { goto fail; } outtot += outlen; //We concatenate iv and cipher text together memcpy(outbuf, iv, iv_len); if (send_msg(sk, outbuf, outtot + iv_len, format) < outtot + iv_len) { goto fail; } EVP_CIPHER_CTX_cleanup(ctx); free(ctx); free(iv); free(outbuf); return outtot; fail: EVP_CIPHER_CTX_cleanup(ctx); free(ctx); free(iv); if (outbuf != NULL) { free(outbuf); } return -1; }
/* * NB: questa funzione restituisce un buffer più grande del dovuto per cui * fare sempre riferimento al valore di output_len */ char* sym_decrypt(unsigned char* cipher, int cipher_len, unsigned char* key, int* output_len){ char* plaintext; int outlen, outlen_tot, n, len, res; int block_size = EVP_CIPHER_block_size(SYM_CIPHER); if(cipher == NULL || key == NULL){ return NULL; } plaintext = (char*)malloc(cipher_len + block_size); EVP_CIPHER_CTX* ctx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX)); EVP_CIPHER_CTX_init(ctx); EVP_DecryptInit(ctx, SYM_CIPHER, key, NULL); len = cipher_len; //passaggio inutile ma serve per mantenere una continuità con le funzioni precedenti /* Decryption */ outlen = 0; outlen_tot = 0;// dim testo output (plaintext) n=0;//dim testo input (ciphertext) while(n/block_size < len/block_size){ EVP_DecryptUpdate(ctx, plaintext+ outlen_tot, &outlen, (char*)cipher+ n, block_size); outlen_tot += outlen; n += block_size; } EVP_DecryptUpdate(ctx, plaintext+ outlen_tot, &outlen, (char*)cipher+ n, len % block_size); outlen_tot += outlen; n += len % block_size; res = EVP_DecryptFinal(ctx, plaintext + outlen_tot, &outlen); /*if(res == 0){ printf("ERROR in decrypting.\n"); return NULL; }*/ outlen_tot += outlen; EVP_CIPHER_CTX_cleanup(ctx); *output_len = outlen_tot; return plaintext; }
void Cipher::Key::set(const char *cipher) { char algoname[64]; clear(); String::set(algoname, sizeof(algoname), cipher); char *fpart = strchr(algoname, '-'); char *lpart = strrchr(algoname, '-'); if(fpart && fpart == lpart) String::set(fpart, sizeof(algoname), fpart + 1); algotype = EVP_get_cipherbyname(algoname); if(!algotype) return; keysize = EVP_CIPHER_key_length((const EVP_CIPHER*)algotype); blksize = EVP_CIPHER_block_size((const EVP_CIPHER*)algotype); }
int pbaes256_decrypt(pubnub_bymebl_t data, uint8_t const* key, uint8_t const* iv, pubnub_bymebl_t *msg) { int result; EVP_CIPHER_CTX *aes256; if (msg->size < data.size + EVP_CIPHER_block_size(EVP_aes_256_cbc()) + 1) { PUBNUB_LOG_ERROR("Not enough room to save AES-256 decrypted data\n"); return -1; } aes256 = EVP_CIPHER_CTX_new(); if (NULL == aes256) { PUBNUB_LOG_ERROR("Failed to allocate AES-256 decryption context\n"); return -1; } result = do_decrypt(aes256, data, key, iv, msg); EVP_CIPHER_CTX_free(aes256); return result; }
void openssl_evp_keyiv() { int i; const EVP_MD *md; const EVP_CIPHER *type; unsigned char salt[32], data[COMM_LEN], *key, *iv; md = EVP_md5(); printf("\nEVP_Md info: type[%d], ", EVP_MD_type(md)); printf("nid[%d], ", EVP_MD_nid(md)); printf("name[%s], ", EVP_MD_name(md)); printf("pkey type[%d], ", EVP_MD_pkey_type(md)); printf("size[%d], ", EVP_MD_size(md)); printf("block size[%d], ", EVP_MD_block_size(md)); type = EVP_des_ecb(); printf("\nEVP_ECB info: encrypto nid[%d], ", EVP_CIPHER_nid(type)); printf("name[%s], ", EVP_CIPHER_name(type)); printf("bock size[%d]", EVP_CIPHER_block_size(type)); key = (unsigned char *)malloc(EVP_CIPHER_key_length(type)); iv = (unsigned char *)malloc(EVP_CIPHER_iv_length(type)); for (i = 0; i < COMM_LEN; i++) memset(&data[i], i, 1); for (i = 0; i < 32; i++) memset(&salt[i], i, 1); EVP_BytesToKey(type, md, salt, data, COMM_LEN, 2, key, iv); printf("\nEVP_key value: "); for (i = 0; i < EVP_CIPHER_key_length(type); i++) printf("%x ", key[i]); printf("\nEVP_iv value: "); for (i = 0; i < EVP_CIPHER_iv_length(type); i++) printf("%x ", iv[i]); printf("\n"); }
BUF_MEM * PACE_STEP1_enc_nonce(const EAC_CTX * ctx, const PACE_SEC * pi) { BUF_MEM * enc_nonce = NULL; BUF_MEM * key = NULL; check((ctx && ctx->pace_ctx && ctx->pace_ctx->ka_ctx && ctx->pace_ctx->ka_ctx->cipher), "Invalid arguments"); key = kdf_pi(pi, NULL, ctx->pace_ctx->ka_ctx, ctx->md_ctx); check(key, "Key derivation function failed"); BUF_MEM_clear_free(ctx->pace_ctx->nonce); ctx->pace_ctx->nonce = randb(EVP_CIPHER_block_size(ctx->pace_ctx->ka_ctx->cipher)); check(ctx->pace_ctx->nonce, "Failed to create nonce"); enc_nonce = cipher_no_pad(ctx->pace_ctx->ka_ctx, ctx->cipher_ctx, key, ctx->pace_ctx->nonce, 1); err: BUF_MEM_clear_free(key); return enc_nonce; }
int cipher_kt_block_size (const EVP_CIPHER *cipher_kt) { return EVP_CIPHER_block_size (cipher_kt); }