【问题标题】:Unable to decrypt the base64 decoded string using private key无法使用私钥解密 base64 解码字符串
【发布时间】:2014-02-19 06:47:19
【问题描述】:

我有一个 base64 加密字符串,并使用 BIO_f_base64() 解码并使用 ofstream(c++ 代码)写入文件(decoded.txt)。

为了解密我使用了下面的命令(终端)

openssl rsautl -decrypt -inkey private.key -in decoded.txt -out plaintext.txt

这将引发错误“RSA_EAY_PRIVATE_DECRYPT 数据大于 mod”。

但是当我通过终端使用base64字符串解码它时

echo "base64 string" | base64 --decode >> terminal_decode.txt

然后运行

openssl rsautl -decrypt -inkey private.key -in terminal_decode.txt -out plaintext.txt

工作正常。我比较了 decode.txt 和 terminal_decode.txt,看起来都一样。

使用encoded.txt文件我无法解密字符串,请帮我解决这个问题

用于解码的代码:-

    char *enstr = new char[200];    
strcpy(enstr,"sX3/ks3+abL5B1O/o/gSywOYv0tACnRkrMxKnBVDT7yhnatfE5ox2mvQz8RyM6MSCtf2exLUz3uIQGnTnk0yqgWzaDgR2ASEXi6ap1pV+1gAPMHBdiMZeNDI86RfleIH/37p7+lW3eyYwnpKJrsHf72jUu9R+aEXZSsEDEDQ1Hw=");
    int len = strlen(enstr);
char *buff = (char *)malloc(len+1);
memset(buff,0,len+1);
    BIO *biomem, *bio64;
bio64 = BIO_new( BIO_f_base64() );
BIO_set_flags(bio64,BIO_FLAGS_BASE64_NO_NL);
biomem  = BIO_new_mem_buf(enstr,len);
biomem = BIO_push(bio64,biomem);
BIO_read(biomem,buff,len);
buff[len]='\0';
ofstream ofs("encoded.txt",std::ios::out);
ofs.write(buff,len);
ofs.close();

【问题讨论】:

  • 如果将terminal_decode.txtdecoded.txt 进行比较会发生什么?我强烈怀疑这根本与解密无关,而与您的 base64 解码代码有关。
  • "base64 string" not Base64 编码,因此没有理由尝试解码并将其保存在terminal_decode.txt
  • @noloader:我认为这个问题的意思是暗示字符串“base64 string”实际上应该替换为最初用于生成decoded.txt的base64字符串。
  • base64 字符串仅编码。如果我使用 ofstream 写入文件可以吗?你想让我分享代码吗?
  • 共享代码,请参考并帮助我解决问题

标签: c++ openssl base64 rsa


【解决方案1】:

ofstream ofs("encoded.txt",std::ios::out); ofs.write(buff,len); ofs.close();

ofstream 将摆弄位,因此您不会在内存中获得确切的表示。我相信你需要:

ofstream ofs("encoded.txt", std::ios::binary);

binary 停止新行处理。

在阅读的时候,相信你会需要:

ifstream ifs("encoded.txt", std::ios::binary);
ifs.unsetf(std::ios::skipws);

这将引发错误“RSA_EAY_PRIVATE_DECRYPT 数据大于 mod”。

这意味着消息中的位数超过了模数中的位数。要继续,请减小消息的大小,使其小于或等于n - 1,其中n 是模数。


使用encoded.txt文件我无法解密字符串,请帮我解决这个问题

你的解密码在哪里?

如果您查看<openssl source>/apps/rsautil.c,您将看到 OpenSSL 是如何做到的。所有实用程序(`encryptdecryptx509smime 等)都有相应的源文件,它们位于<openssl source>/apps

这是openssl rsautil 在从命令行设置选项后所做的事情。参见第 275 行:

switch(rsa_mode) {

  case RSA_VERIFY:
    rsa_outlen  = RSA_public_decrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
    break;

  case RSA_SIGN:
    rsa_outlen  = RSA_private_encrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
    break;

  case RSA_ENCRYPT:
    rsa_outlen  = RSA_public_encrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
    break;

  case RSA_DECRYPT:
    rsa_outlen  = RSA_private_decrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad);
    break;
}
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 2015-07-31
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多