使用C 中的OPENSL RSA函数解密消息错误

Errors decrypting message using OpenSSL RSA functions in C++

本文关键字:解密 消息 错误 函数 RSA 中的 OPENSL 使用      更新时间:2023-10-16

我已经为此挣扎了一段时间。当我运行程序时,有时我会看到这些错误:

bad decrypt
140380701197976:error:0606506D:digital envelope 
routines:EVP_DecryptFinal_ex:wrong final block length:evp_enc.c:518:

有时,我看到这些错误:

RSA operation error
139986632922776:error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error:rsa_pk1.c:273:
139986632922776:error:04065072:rsa 
routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed:rsa_eay.c:602:
Error reading password from BIO
Error getting password

有时候,我根本看不到任何错误!我正在使用镀茄仪(Galliumos)跑步,这是一种为Chrome硬件制成的Ubuntu味道。

我想念什么?我看了看,找不到任何非常相关的东西。供您参考,我在下面附上了代码。我认为我将错误范围缩小到了最后两个命令之一,但我不是积极的。

#include <cstdlib>
#include <string>
using namespace std;
int main()
{
    string bob_keys, alice_plaintext, alice_encrypted, bob_decrypted;
    // ----- USER INPUT -----
    // TODO: switch to user input
    bob_keys = "bob_keys.pem";
    bob_decrypted = "bob_decrypted.txt";
    alice_encrypted = "alice_encrypted.txt";
    alice_plaintext = "alice_plaintext.txt";
    // ----- CONFIDENTIALITY: MESSAGE ENCRYPTION -----
    // generate session key
    system("openssl rand -base64 64 -out key.bin");
    // encrypt message using session key
    system(("openssl enc -aes-128-cbc -salt -in " + alice_plaintext 
        + " -out alice_plaintext.txt.enc -pass file:./key.bin").c_str());
    // encrypt session key using Bob's public key
    system(("openssl rsautl -encrypt -inkey " + bob_keys 
        + " -pubin -in key.bin -out key.bin.enc").c_str());
    // write encrypted message and encrypted session key to file
    system(("cat alice_plaintext.txt.enc > " + alice_encrypted).c_str());
    system(("echo >> " + alice_encrypted).c_str());
    system(("cat key.bin.enc >> " + alice_encrypted).c_str());
    // ----- CONFIDENTIALITY: MESSAGE DECRYPTION -----
    // get encrypted message and encrypted session key from file (and remove newlines)
    system(("head -1 " + alice_encrypted + " > message.bin.enc").c_str());    
    system("tr -d 'n' < message.bin.enc > temp.bin && mv temp.bin message.bin.enc");
    system(("tail -1 " + alice_encrypted + " > key.bin.enc").c_str());    
    // decrypt the key using Bob's private key
    system(("openssl rsautl -decrypt -inkey " + bob_keys 
        + " -in key.bin.enc -out key.bin").c_str());
    // decrypt the message using the decrypted key
    system(("openssl enc -d -aes-128-cbc -in message.bin.enc -out "
        + bob_decrypted + " -pass file:./key.bin").c_str());
    return 0;
}

您在二进制文件上使用ˋeheadˋ和ˋtailˋ。在此之前,您设法逃脱了可以将二进制解释为文本的许多陷阱,但是这里最终失败了。您的密文完全可能包含新线字符,如果找到这些字符,则您的密文将不正确。您要么仅使用二进制文件,要么应该基于64编码您的密文。

请注意,您设法按照您的方式来规避C/C 的使用是很棒的,但是最后一个笑声在您身上。您使用的是密码而不是键,结果与仅使用AES密钥并不相同。要聪明,然后使用C库。或者,如果您喜欢C ,请使用加密 或Bothan。并学习如何实际编程,而不是侵入勇气。因为您 - 最终 - 将是您自己黑客攻击最大的人。