我想在openSSL中使用PKCS7_encrypt()
和PKCS7_decrypt()
函數進行加密和解密。我在openSSL Demo中使用了這個例子。我想要做的是加密一個格式爲char*
的消息,並使用那個char*
進行解密。我不想讀取和寫入文件。這裏是加密代碼,完美的作品,並沒有問題:在openssl中使用PKCS7_decrypt()解密char *
in = BIO_new_file("encr.txt", "r");
if (!in)
return 0;
/* encrypt content */
p7 = PKCS7_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
if (!p7)
return 0;
char* chEnc = new char[1000];
BIO* memorybio = BIO_new(BIO_s_mem());
BIO* base64bio = BIO_new(BIO_f_base64());
BIO* outbio = BIO_push(base64bio, memorybio);
/* Copy PKCS#7 */
long ll = i2d_PKCS7_bio(outbio, p7);
BIO_flush(outbio);
BIO_set_flags(memorybio, BIO_FLAGS_MEM_RDONLY);
BIO_get_mem_data(memorybio, &chEnc);
cout << chEnc << "\n";
現在,當我想要做反向和解密char*
chEnc,我做了如下:
BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *rcert = NULL;
EVP_PKEY *rkey = NULL;
PKCS7 *p7 = NULL;
int ret = 1;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in recipient certificate and private key */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
return 0;
rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
BIO_reset(tbio);
rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
if (!rcert || !rkey)
return 0;
BIO* memorybio = BIO_new(BIO_s_mem());
int iLength = BIO_puts(memorybio, chEnc);
BIO* base64bio = BIO_new(BIO_f_base64());
BIO* inbio = BIO_push(base64bio, memorybio);
/* Copy PKCS#7 */
BIO_flush(inbio);
BIO_set_flags(inbio, BIO_FLAGS_MEM_RDONLY);
p7 = d2i_PKCS7_bio(inbio, &p7);
if (!PKCS7_decrypt(p7, rkey, rcert, out, 0))
return 0;
ret = 0;
if (ret) {
fprintf(stderr, "Error Signing Data\n");
ERR_print_errors_fp(stderr);
}
if (p7)
PKCS7_free(p7);
if (rcert)
X509_free(rcert);
if (rkey)
EVP_PKEY_free(rkey);
if (in)
BIO_free(in);
if (out)
BIO_free(out);
if (tbio)
BIO_free(tbio);
return ret;
的問題是PKCS7_decrypt
不起作用,它不會解密爲out
變量。行if (!PKCS7_decrypt(p7, rkey, rcert, out, 0)) return 0;
後,它從函數返回。解密過程是否正確?我可以使用其他的openSSL API來轉換嗎?
期待您的建議和意見。
謝謝