Search code examples
copensslaeslibcrypto

Decrypting doesn't result in the same output as before encryption


I can't figure out why block is not the same before and after the encrypt and decrypt functions are run.

#include <stdio.h>
#include <sys/types.h>
#include <openssl/aes.h>

int main(void)
{
  AES_KEY aesKey;
  char key[] = "secretsecretsecr";
  char block[] = "somesecretishere";
  char cypher [16];
  int i = 0;
  AES_set_encrypt_key((u_char *)key,0x80,(AES_KEY *)&aesKey);
  printf("\n");
  for (i = 0; i < 0x10; i = i + 1) {
      printf("%i ", block[i]);
  }
  printf("\n");
  AES_encrypt((u_char *)block,(u_char *)cypher,(AES_KEY *)&aesKey);
  AES_decrypt((u_char *)cypher,(u_char *)block,(AES_KEY *)&aesKey);
  printf("\n");
  for (i = 0; i < 0x10; i = i + 1) {
      printf("%i ", block[i]);
  }
  printf("\n");
}

This is not production code, I was just experimenting with the OpenSSL library. I know these functions handle input in blocks of 16 bytes but even still this isn't working the way I expected it to.


Solution

  • In order to decipher the block, you must initialize the key for decryption prior to calling AES_decrypt:

    AES_set_decrypt_key((u_char *)key, 0x80, (AES_KEY *)&aesKey);
    

    Try this modified version:

    #include <stdio.h>
    #include <sys/types.h>
    #include <openssl/aes.h>
    
    int main(void) {
        AES_KEY aesKey;
        unsigned char key[] = "secretsecretsecr";
        unsigned char block[] = "somesecretishere";
        unsigned char cypher[16];
        int i;
    
        printf("\n");
        for (i = 0; i < 0x10; i++) {
            printf("%i ", block[i]);
        }
        printf("\n");
    
        AES_set_encrypt_key(key, 128, &aesKey);
        AES_encrypt(block, cypher, &aesKey);
    
        AES_set_decrypt_key(key, 128, &aesKey);
        AES_decrypt(cypher, block, &aesKey);
    
        printf("\n");
        for (i = 0; i < 0x10; i++) {
            printf("%i ", block[i]);
        }
        printf("\n");
        return 0;
    }