c - OpenSSL CBC Encrypt IV 损坏
问题描述
在使用 C 的 OpenSSL CBC 模式将该信息写入文件之前,我正在尝试加密“客户”信息。
当我尝试加密文本时,它不会创建加密输出,它似乎也会破坏给定的 IV 它如下所示
BANK: create-user bob 1234 1
PLAINTEXT: bob
IV: 9289437166649966
ENCRYPTION OF NAME OUTPUT:
0010 - <SPACES/NULS> <-- encrypting name outputs nothing
PLAINTEXT: 1234
IV: ��=H�W��I��%%��� <-- IV becomes unusable afterwards
ENCRYPTION OF PIN OUTPUT:
0010 - <SPACES/NULS> <-- Still no encryption output
无论输入的 IV 如何,损坏的 IV 始终相同
我生成加密的代码是这样的:
unsigned char *cipher_name, *cipher_pin, IV[16], *IV_cpy*plaintext_n, *plaintext_p;
cipher_name = (unsigned char *) calloc(1000, sizeof(unsigned char));
cipher_pin = (unsigned char *) calloc(1000, sizeof(unsigned char));
plaintext_n = (unsigned char *) calloc(1000, sizeof(unsigned char));
plaintext_p = (unsigned char *) calloc(1000, sizeof(unsigned char));
int cipher_len;
.
.
.
rand_gen(IV);
IV_cpy = (unsigned char *)malloc(strlen((char *)IV));
memcpy(IV_cpy, IV, strlen((char *)(IV)));
strcpy((char *)plaintext_n,cmd[1]);
cipher_len = encrypt(plaintext_n, strlen((char *) plaintext_n), IV,cipher_name);
BIO_dump_fp (stdout, (const char *)cipher_name, cipher_len);
strcpy((char *)plaintext_p, cmd[2]);
memcpy(IV_cpy, IV, strlen((char *)(IV)));
cipher_len = encrypt(plaintext_p, strlen((char *) plaintext_p), IV, cipher_pin);
BIO_dump_fp (stdout, (const char *)cipher_pin, cipher_len);
我省略了打印语句以提高可读性。
生成 IV 的代码是:
void rand_gen(unsigned char *ret_val) {
int i, random;
char rand_int[2];
ret_val[0] = '\0';
srand(time(0));
for(i = 0; i < 16; i++) {
random = rand() % 10;
if(random == 0) {
random = 1;
}
sprintf(rand_int, "%d", random);
strcat((char *)ret_val, rand_int);
}
}
加密函数的代码是
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char
*ciphertext, unsigned char *IV) {
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, IV)) handleErrors();
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors();
ciphertext_len = len;
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
密钥在其他地方可用,这就是为什么它不在函数 args 中
加密输出的内容:
0010 - <SPACES/NULS>
应该输出什么加密:
0000 - c7 2b 0a 46 7f 8e 2f e1-7d e6 a3 20 99 c2 7d 2b .+.F../.}.. ..}+
解决方案
推荐阅读
- java - 如何从 System.out.printf Java 中修剪空格
- python - 从 Glassdoor 网站获取工资值的正确路径链接是什么?请看截图
- laravel - 在 Laravel 8 中按 ID 子字符串查找会话
- authentication - 多租户 ASP.NET 核心
- matlab - Matlab Structures:如何比较结构的内容?收到以下错误
- java - Java:如何填充两个数组,在两者之间交替
- javascript - 使用 Nuxt 内容模块的降价文件的“无效 URL”错误
- fortran - 适用于 Linux 的 Windows 子系统上的 GNU Fortran 编译器 - 将内部函数传递给另一个过程时出现分段错误
- docker - Dockerfile:复制zip并打开它
- javascript - 遍历数组和其中的平均值/求和值