c - OpenSSL 和 AES

标签 c linux cryptography openssl aes

我正在使用 OpenSSL lib 并使用 AES 加密/解密获得非常奇怪的效果:如果我将更改加密消息中的某些字节并对其进行解密,我将看到原始消息的一部分,这是不应该的是。这是源代码:

#include <openssl/evp.h> 
#include <string.h>

int do_crypt(void) 
{  
 int outlen, inlen;  
 FILE *in, *out;  
 in = fopen("in.txt", "r"); 
 out = fopen("out.txt", "w"); 
 unsigned char key[32];
 strcpy(key, "10000000000000000000000000000002"); 
 unsigned char iv[8];
 unsigned char inbuf[BUFSIZE], outbuf[BUFSIZE];  
 EVP_CIPHER_CTX ctx;  
 const EVP_CIPHER * cipher;    


 EVP_CIPHER_CTX_init(&ctx);   
 cipher = EVP_aes_256_cfb(); 
 EVP_EncryptInit(&ctx, cipher, key, 0); 

while(1) {                    
 inlen = fread(inbuf, 1, BUFSIZE, in);  
 if(inlen <= 0) break;  
 if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) return 0;  
 fwrite(outbuf, 1, outlen, out);  
 }    

if(!EVP_EncryptFinal(&ctx, outbuf, &outlen)) return 0;  
 fwrite(outbuf, 1, outlen, out);  
 EVP_CIPHER_CTX_cleanup(&ctx);  
 return 1;  
} 

int do_decrypt(char *infile) 
{  
 int outlen, inlen;  
 FILE *in, *out;  
 in = fopen("out.txt", "r"); 
 out = fopen("out2.txt", "w"); 
 unsigned char key[32];
 strcpy(key, "10000000000000000000000000000002"); 
 unsigned char iv[8];  
 unsigned char inbuf[BUFSIZE], outbuf[BUFSIZE];  
 EVP_CIPHER_CTX ctx;  

 EVP_CIPHER_CTX_init(&ctx);  
 EVP_DecryptInit(&ctx, EVP_aes_256_cfb(), key, 0);  

 while(1) {  
 inlen = fread(inbuf, 1, BUFSIZE, in);  
 if(inlen <= 0) break;  
 if(!EVP_DecryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) return 0; 
 fwrite(outbuf, 1, outlen, out);  
 }  

 if(!EVP_DecryptFinal(&ctx, outbuf, &outlen)) return 0;  
 fwrite(outbuf, 1, outlen, out);  
 EVP_CIPHER_CTX_cleanup(&ctx);  
 return 1;  
} 

main(int argc, char **argv){ 
if(atoi(argv[1]) == 1) 
    do_crypt(0); 
if(atoi(argv[1]) == 2) 
    do_decrypt(0);    
} 

有什么问题吗?

最佳答案

错误的是你期望整个消息变得不可读,因为一个字节被更改了。

消息的哪些部分变得不可读取决于所选的加密模式。你正在使用循环流化床。这意味着,如果您更改密文中的单个字节,相应的字节和之后的 block 就会被破坏,之后密码会从错误中恢复。

PCBC错误后将破坏所有输出。但它仍然没有检测到错误。

我建议添加身份验证(MAC,或具有集成身份验证的模式,例如 AES-GCM)。

关于c - OpenSSL 和 AES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9909739/

相关文章:

c - usleep() 计算耗时表现得很奇怪

mysql - 如何正确解决 mySQL 上的 ERROR 1044?这里的其他答案不起作用

rust - 如何从作为十六进制编码字符串给出的模数和指数构造公钥?

linux - epoll 为 timerfd 报告 EPOLLIN 后,read() 返回 EAGAIN

linux - "error occurred while loading or saving configuration information"

encryption - 用一次一密编码的信息能否与随机噪声区分开来?

php - 用PHP加密的openssl需要用Ruby解密

c - 如何避免全局常量的 "multiple definition"错误?

c - 使用 Visual Studio 结合 Intel Fortran,如何解决使用不同类型的名称重整问题

c++ - 将 DKM 项目链接到内核镜像 (VIP) 项目作为 VxWorks Workbench4 中的子项目/额外模块