OpenSSL CBC加密IV的损坏

时间:2018-11-21 23:00:48

标签: c encryption openssl

我正在尝试使用“ 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../.}.. ..}+

0 个答案:

没有答案