我想在openSSL中使用PKCS7_encrypt()
和PKCS7_decrypt()
函数进行加密和解密。我在 openSSL Demo 中使用了这个例子。我想要做的是加密格式的消息char*
并使用它解密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
变量。在 line 之后if (!PKCS7_decrypt(p7, rkey, rcert, out, 0)) return 0;
,它从函数返回。解密程序是否正确?我应该使用openSSL的其他API来转换还是什么?
期待您的建议和意见。
谢谢