2014-02-19 69 views
0

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

用于解密我用下面的命令(终端)

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

这会引发错误“比模更大RSA_EAY_PRIVATE_DECRYPT数据”。

但是当我使用

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

通过终端解码的base64它串并运行

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(); 
+1

如果将'terminal_decode.txt'与'decoded.txt'进行比较,会发生什么情况?我强烈怀疑这与解密完全无关,并且与你的base64解码代码有关。 –

+0

“base64 string”是* not * Base64编码,因此没有理由尝试解码并将其保存在'terminal_decode.txt'中。 – jww

+0

@noloader:我认为这个问题意味着暗示字符串“base64 string”实际上应该被最初用于生成'decoded.txt'的base64字符串替换。 –

回答

0

ofstream的OFS(“encoded.txt ”的std :: IOS ::出来); 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数据”。

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


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

哪里是你的解密代码?

如果你看看<openssl source>/apps/rsautil.c,那么你会看到OpenSSL是如何做到的。所有实用程序(`encrypt,decrypt,x509,smime等)都有相应的源文件,它们位于<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; 
} 
...