OpenSSL RSA解密随机失败C / C ++

时间:2018-09-05 11:34:35

标签: c++ encryption openssl rsa

我正在实现RSA算法,在该算法中,我分别从.crt和.pem证书读取公共和私有密钥。它可以正确加密数据,但问题出在解密上。有时它可以很好地解密,有时它会出现以下错误:

  

解密消息时出错:error:04099079:rsa   例程:RSA_padding_check_PKCS1_OAEP_mgf1:oaep解码错误。

如果满足以下条件,则解密失败

if ((decrypt_len = RSA_private_decrypt(strlen(c), (unsigned char*)c,
        (unsigned char*)decrypt, rsa, RSA_PKCS1_OAEP_PADDING)) == -1)

代码块如下:

void DecryptRSA(const char *message)
{
    char *privateCertPath = "privateCertificate.pem";

    const char *msg = message; //message in base64 characters
    BIO *bo = BIO_new_file(privateCertPath, "rb");

    EVP_PKEY *pri;
    OpenSSL_add_all_algorithms();
    pri = PEM_read_bio_PrivateKey(bo, NULL, NULL,  NULL);
    if (pri == NULL) {
        /* Error */
    }

    RSA* rsa = EVP_PKEY_get1_RSA(pri);

    unsigned char *decrypt = (unsigned char *) malloc(RSA_size(rsa));
    int decrypt_len;
    char *err = (char *) malloc(130);
    string msgascii = base64_decode(msg); //converting 
    const char *c = msgascii.c_str();   

    if ((decrypt_len = RSA_private_decrypt(strlen(c), (unsigned char*)c,
        (unsigned char*)decrypt, rsa, RSA_PKCS1_OAEP_PADDING)) == -1)
    {
        ERR_load_crypto_strings();
        ERR_error_string(ERR_get_error(), err);
        fprintf(stderr, "Error decrypting message: %s\n", err);     
    }

    printf("%s", decrypt);

    RSA_free(rsa);
    BIO_free(bo);
    free((char*)msg);
    free((char*)c);
    free(decrypt);  
    free(err);  
}

1 个答案:

答案 0 :(得分:1)

在if条件中使用strlen(c)导致当加密字符包含空字符时char数组终止,所以我改用msgascii.size()来解决问题。