抱歉愚蠢的问题,我看过很多例子,但无法找到答案。 尝试使用rsa加密和解密文件:
加密
ptext = (unsigned char *)malloc(key_size);
ctext = (unsigned char *)malloc(key_size);
while (1) {
inlen = _read(in, ptext, key_size);
if (inlen <= 0) break;
outlen = RSA_public_encrypt(inlen, ptext, ctext, pubKey,
RSA_PKCS1_PADDING);
if (outlen != RSA_size(pubKey)) exit(-1);
_write(out, ctext, outlen);
}
解密:
while (1) {
inlen = _read(in, ctext, key_size);
printf("Read %i bytes\n", inlen);
if (inlen <= 0) break;
outlen = RSA_private_decrypt(key_size-11, ctext, ptext, privKey, RSA_PKCS1_PADDING);
printf("RSA returns %i\n", outlen);
if (outlen < 0)
{
fprintf(stderr, "OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
exit(0);
}
_write(out, ptext, outlen);
}
节目输出:
Read 431 bytes
RSA returns -1
OpenSSL error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error
key_size或key_size-11 - &gt;没有变化。 帮助plz绕过这个错误。
答案 0 :(得分:0)
对于RSA解密,flen
必须是RSA_size(pubkey)
,而不是RSA_size(pubkey) - 11
。因此像
outlen = RSA_private_decrypt(RSA_size(pubKey), ctext, ptext, privKey, RSA_PKCS1_PADDING);
应该有效。解密的明文应包含在ctext[0]
... ctext[outlen-1]
。
答案 1 :(得分:0)
这就是我在我的项目中使用RSA crypt函数的方法。尝试与您的实施进行比较
int rsa_oaep_encrypt(EVP_PKEY *publicKey, const unsigned char *plaintext, const size_t plaintextLen, unsigned char *ciphertext, size_t *ciphertextLen)
{
int sts = -1;
if ( (*ciphertextLen = RSA_public_encrypt(plaintextLen, plaintext, ciphertext, publicKey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) > 0)
sts = 0;
return sts;
}
int rsa_oaep_decrypt(EVP_PKEY *privateKey, const unsigned char *ciphertext, const size_t ciphertextLen, unsigned char *plaintext, size_t *plaintextLen)
{
int sts = -1;
if ( (*plaintextLen = RSA_private_decrypt(ciphertextLen, ciphertext, plaintext, privateKey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) > 0)
sts = 0;
return sts;
}