Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int AES_encrypt(const int nrounds, uint8_t *key_data, const int key_data_len, uint8_t *plaintext, int *len, uint8_t *ciphertext)
- {
- int rc = -1;
- int c_len = *len;
- if(key_data_len <= 0 || key_data_len < AES_BITMODE){
- lowLog("%s","Insufficient AES key length!");
- return rc;
- if(c_len <= 0 || (c_len%8) != 0){
- lowLog("%s","Insufficient plaintext length!");
- return rc;//insufficient data length
- }
- //"opaque" decryption ctx structure that libcrypto uses to record status of enc/dec operations
- EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new();
- int i;// nrounds = 5;
- uint8_t key[AES_BITMODE]={}, iv[AES_BITMODE]={};
- /* 2 bytes to salt, TODO check complex/random salt which can be used*/
- uint8_t salt[] = {0x34, 0xff};
- /* AES Initialization++
- * Gen key & IV for AES 128 CBC mode. A SHA1 digest is used to hash the supplied key material.
- * nrounds is the number of times the we hash the material. More rounds are more secure but
- * slower.
- */
- i = EVP_BytesToKey(EVP_aes_128_ctr(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
- if (i != 16) {
- lowLog("Key size is %d bits - should be 128 bitsn", i*8);
- return rc;
- EVP_CIPHER_CTX_init(e_ctx);
- EVP_EncryptInit_ex(e_ctx, EVP_aes_128_ctr(), NULL, key, iv);
- //--
- /*IMPORTANT: Disable padding since we need to get ciphertext exact as size of plaintext
- Ensure that plaintext to be provided everytime is exact 16 bytes or multiple of 16 bytes
- */
- /*unsigned char *ciphertext = (unsigned char*)malloc(c_len);*/
- EVP_CIPHER_CTX_set_padding(e_ctx, 0);
- /* update ciphertext, c_len is filled with the length of ciphertext generated,
- *len is the size of plaintext in bytes */
- if(EVP_EncryptUpdate(e_ctx, ciphertext, &c_len, plaintext, *len) == EVP_FAILURE)
- return rc;
- /*Refer below DOC NOTE from openssl:-
- If padding is disabled then EVP_EncryptFinal_ex() will not encrypt any more data and
- it will return an error if any data remains in a partial block:
- that is if the total data length is not a multiple of the block size.*/
- /*if(EVP_EncryptFinal_ex(e_ctx, ciphertext+c_len, &f_len) == EVP_FAILURE)
- return rc;*/
- EVP_CIPHER_CTX_free(e_ctx);
- //*len = c_len + f_len;
- //cout<<"cipher len::"<<c_len<<endl;//ciphering length check
- return 0;
- }
Add Comment
Please, Sign In to add comment