解密不会产生与加密前相同的输出

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

我不明白为什么block加密和解密函数前后不一样运行。

#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");
}

这不是生产代码,我只是在试验 OpenSSL 库。我知道这些函数以 16 字节为单位处理输入,但仍然无法按我预期的方式工作。

为了解密该块,您必须在调用 AES_decrypt 之前初始化解密密钥:

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

试试这个修改后的版本:

#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;
}