SymmetricEncryptionBox.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "Openssl_crypto.h"
  2. #include "SymmetricEncryptionBox.h"
  3. // increments last 4 bytes (in big-endian order)
  4. uint32_t SymmetricEncryptionBox::aes_gcm_increment_iv_internal_call(uint8_t* iv) {
  5. uint32_t counter;
  6. for(counter=11;counter>7;counter--)
  7. {
  8. if(iv[counter] == 0xff)
  9. {
  10. if(counter - 1 == 7)
  11. return 0xff;
  12. iv[counter-1] = 0x01;
  13. iv[counter] = 0x0;
  14. }
  15. else
  16. iv[counter] += 1;
  17. }
  18. return 0;
  19. }
  20. void SymmetricEncryptionBox::set_symmetric_key(uint8_t* given_key)
  21. {
  22. uint32_t counter;
  23. for(counter=0; counter<16; counter++)
  24. symmetric_key[counter] = given_key[counter];
  25. }
  26. void SymmetricEncryptionBox::get_symmetric_key(uint8_t* op_key)
  27. {
  28. uint32_t counter;
  29. for(counter=0; counter<16; counter++)
  30. op_key[counter] = symmetric_key[counter];
  31. }
  32. // TODO: IMPORTANT - CHECK IF WE NEED TO DO THE AES GCM INCREMENT IV FOR DECRYPTION TOO.
  33. uint32_t SymmetricEncryptionBox::encrypt_decrypt(int enc, uint8_t* plaintext, uint32_t plaintext_length, uint8_t* ciphertext, uint32_t* ciphertext_length)
  34. {
  35. uint8_t tag[16];uint32_t counter;
  36. if(enc == 0)
  37. {
  38. for(counter=0;counter<16;counter++)
  39. tag[counter] = plaintext[counter + plaintext_length];
  40. }
  41. uint32_t return_status = aes_gcm_128(enc, symmetric_key, iv, plaintext, plaintext_length, ciphertext, ciphertext_length, tag);
  42. if(enc == 1)
  43. {
  44. for(counter=0;counter<16;counter++)
  45. ciphertext[counter + *ciphertext_length] = tag[counter];
  46. *ciphertext_length=*ciphertext_length + 16;
  47. }
  48. if(return_status == 0)
  49. aes_gcm_increment_iv_internal_call(iv);
  50. return return_status;
  51. }