Guest User

Untitled

a guest
Oct 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <opensslevp.h>
  3.  
  4. unsigned char key[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  5. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
  6.  
  7. unsigned char nonce[13] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
  8. 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c};
  9.  
  10. unsigned char test[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  11. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
  12.  
  13. unsigned char AAD[1] = {0x01};
  14.  
  15.  
  16. void encrypt()
  17. {
  18.  
  19. unsigned char output[16];
  20. unsigned char tag[4];
  21. int ciphertext_len = 0;
  22. int len = 0;
  23.  
  24. // Create Cipher
  25. EVP_CIPHER_CTX *ctx;
  26.  
  27. // Create and Initialize context
  28. if (!(ctx = EVP_CIPHER_CTX_new())) {
  29. printf("Problem creating Cipher");
  30. }
  31.  
  32. // Initialize Encryption Operation
  33. if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_ccm(), NULL, NULL, NULL)) {
  34. printf("Error Initializing Encryption");
  35. }
  36.  
  37. // Set nonce length (setting to 13 bytes)
  38. if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 13, NULL)) {
  39. printf("Error setting IV length");
  40. }
  41.  
  42. // Set tag length to 4 bytes
  43. if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 4, NULL)) {
  44. printf("Error setting tag size");
  45. }
  46.  
  47. // Initialize Key and IV (nonce)
  48. if (1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, nonce)) {
  49. printf("Error initializing Key and IV");
  50. }
  51.  
  52. // THIS IS WHERE THE ISSUE IS //
  53. // Provide AAD Data
  54. if (1 != EVP_EncryptUpdate(ctx, NULL, &len, AAD, sizeof(AAD))) {
  55. printf("Error providing Additional Authenticated Data");
  56. }
  57. // END ISSUE
  58.  
  59. // Provide message to be encrypted and obtain encrypted output
  60. if (1 != EVP_EncryptUpdate(ctx, output, &len, test, sizeof(test))) {
  61. printf("Error obtaining encrypted output");
  62. }
  63.  
  64. ciphertext_len = len;
  65.  
  66. // Finalize encryption
  67. if (1 != EVP_EncryptFinal(ctx, output + len, &len)) {
  68. printf("Failed to finalize encryption");
  69. }
  70.  
  71. // Get the tag
  72. if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 4, tag)) {
  73. printf("Error collecting tag");
  74. }
  75.  
  76. // Clean up
  77. EVP_CIPHER_CTX_free(ctx);
  78.  
  79. printf("nCiphertext Length = %i", ciphertext_len);
  80.  
  81. for (int i = 0; i < ciphertext_len; i++) {
  82. printf("nByte [%i] = %i", i, output[i]);
  83. }
  84.  
  85. for (int i = 0; i < sizeof(tag); i++) {
  86. printf("nMAC [%i] = %i", i, tag[i]);
  87. }
  88. }
Add Comment
Please, Sign In to add comment