我正在玩 AES 加密,我遇到了这个问题。我在网上某处找到了一个代码示例,并尝试使用它。(我正在使用 Gladman AES 库)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include "aes.h"
void encrypt(const char *fileIn, const char *fileOut, const unsigned char *key);
void decrypt_string(const char *fileIn, const unsigned char *key);
int main() {
const unsigned char key[] = "password";
srand(time(NULL));
aes_init();
encrypt("TEST.raw", "TEST.raw.encrypted", key);
decrypt_string("TEST.raw.encrypted", key);
return 0;
}
void encrypt(const char *fileIn, const char *fileOut, const unsigned char *key) {
int i;
aes_encrypt_ctx ctx[1];
unsigned char iv[16]; /* initialisation vector */
unsigned char inBuffer[200], outBuffer[200];
FILE *inFile = fopen(fileIn, "rb");
FILE *outFile = fopen(fileOut, "wb");
/* pick a random initialisation vector */
for(i = 0; i < 16; ++i)
iv[i] = rand() & 0xFF;
fwrite(iv, 1, 16, outFile);
aes_encrypt_key256(key, ctx);
while((i = fread(inBuffer, 1, sizeof(inBuffer), inFile)) > 0) {
aes_ofb_encrypt(inBuffer, outBuffer, i, iv, ctx);
fwrite(outBuffer, 1, i, outFile);
}
aes_ofb_encrypt(inBuffer, outBuffer, i, iv, ctx);
fwrite(outBuffer, 1, i, outFile);
fclose(inFile);
fclose(outFile);
}
void decrypt_string(const char *fileIn, const unsigned char *key) {
int i,j;
aes_encrypt_ctx ctx[1];
unsigned char iv[16]; /* initialisation vector */
unsigned char inBuffer[200], outBuffer[200];
FILE *inFile = fopen(fileIn, "rb");
//FILE *outFile = fopen(fileOut, "wb");
/* read initialization vector from file */
if(fread(iv, 1, 16, inFile) < 16)
return; /* error: file doesn't even contain an initialisation vector */
aes_encrypt_key256(key, ctx);
while((i = fread(inBuffer, 1, sizeof(inBuffer), inFile)) > 0) {
aes_ofb_decrypt(inBuffer, outBuffer, i, iv, ctx);
printf("%s", outBuffer);
}
fclose(inFile);
}
现在一切正常,文件被正确解密。
但是,当我获取加密文件并尝试使用decrypt_string() 函数再次对其进行解密时,它无法正确解密。它仅在程序运行时有效。现在我一直在搜索,发现aes.h中的注释,可能与aes_mode_reset()有关。但是我只是在学习,所以我不太了解。所以我会很感激我能得到的任何帮助。