Guest User

Untitled

a guest
Oct 17th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. int AES_encrypt(const int nrounds, uint8_t *key_data, const int key_data_len, uint8_t *plaintext, int *len, uint8_t *ciphertext)
  2. {
  3. int rc = -1;
  4. int c_len = *len;
  5. if(key_data_len <= 0 || key_data_len < AES_BITMODE){
  6. lowLog("%s","Insufficient AES key length!");
  7. return rc;
  8.  
  9. if(c_len <= 0 || (c_len%8) != 0){
  10. lowLog("%s","Insufficient plaintext length!");
  11. return rc;//insufficient data length
  12. }
  13.  
  14. //"opaque" decryption ctx structure that libcrypto uses to record status of enc/dec operations
  15. EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new();
  16. int i;// nrounds = 5;
  17. uint8_t key[AES_BITMODE]={}, iv[AES_BITMODE]={};
  18. /* 2 bytes to salt, TODO check complex/random salt which can be used*/
  19. uint8_t salt[] = {0x34, 0xff};
  20.  
  21.  
  22. /* AES Initialization++
  23. * Gen key & IV for AES 128 CBC mode. A SHA1 digest is used to hash the supplied key material.
  24. * nrounds is the number of times the we hash the material. More rounds are more secure but
  25. * slower.
  26. */
  27. i = EVP_BytesToKey(EVP_aes_128_ctr(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
  28. if (i != 16) {
  29. lowLog("Key size is %d bits - should be 128 bitsn", i*8);
  30. return rc;
  31.  
  32.  
  33. EVP_CIPHER_CTX_init(e_ctx);
  34. EVP_EncryptInit_ex(e_ctx, EVP_aes_128_ctr(), NULL, key, iv);
  35. //--
  36.  
  37. /*IMPORTANT: Disable padding since we need to get ciphertext exact as size of plaintext
  38. Ensure that plaintext to be provided everytime is exact 16 bytes or multiple of 16 bytes
  39. */
  40. /*unsigned char *ciphertext = (unsigned char*)malloc(c_len);*/
  41. EVP_CIPHER_CTX_set_padding(e_ctx, 0);
  42.  
  43. /* update ciphertext, c_len is filled with the length of ciphertext generated,
  44. *len is the size of plaintext in bytes */
  45. if(EVP_EncryptUpdate(e_ctx, ciphertext, &c_len, plaintext, *len) == EVP_FAILURE)
  46. return rc;
  47.  
  48. /*Refer below DOC NOTE from openssl:-
  49. If padding is disabled then EVP_EncryptFinal_ex() will not encrypt any more data and
  50. it will return an error if any data remains in a partial block:
  51. that is if the total data length is not a multiple of the block size.*/
  52. /*if(EVP_EncryptFinal_ex(e_ctx, ciphertext+c_len, &f_len) == EVP_FAILURE)
  53. return rc;*/
  54.  
  55. EVP_CIPHER_CTX_free(e_ctx);
  56. //*len = c_len + f_len;
  57. //cout<<"cipher len::"<<c_len<<endl;//ciphering length check
  58. return 0;
  59. }
Add Comment
Please, Sign In to add comment