2014-02-19 72 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; 
} 
...