Openssl RSA在C中加密和解密

时间:2018-05-17 09:19:55

标签: c encryption openssl rsa pem

我有一个示例代码,它使用PEM私钥加密消息并使用PEM公钥解密,但最后解密结果为空。

    const char * msg = "this is a test message";
    //********************Encrypt*******************************
    if ((pFile = fopen("private.pem", "rt")) &&
        (rsa = PEM_read_RSAPrivateKey(pFile, NULL, passwd_callback, (void*)pcszPassphrase)))
    {
        fprintf(stderr, "Private key read.\n");

        RSA_private_encrypt(strlen(msg), (unsigned char *)msg, encrypted, rsa, RSA_PKCS1_PADDING);
        fclose(pFile);
    }
    //********************Decrypt*******************************
    pFile = fopen("pubkey.pem", "rt");
    if (rsa = PEM_read_RSAPublicKey(pFile, NULL, NULL, NULL))
    {
        RSA_public_decrypt(strlen((char *)encrypted), encrypted, decrypted, rsa, RSA_PKCS1_PADDING);
        ERR_load_crypto_strings();
        char * err = (char *)malloc(130);
        ERR_error_string(ERR_get_error(), err);
        fprintf(stderr, "Error decrypting message: %s\n", err);
    }

因此RSA_public_decrypt的输出为1但解密的字符串为空。

错误消息:解密消息时出错:错误:0407008A:rsa例程:RSA_padding_check_PKCS1_type_1:填充无效

1 个答案:

答案 0 :(得分:3)

您的输入消息msg是一个以空字符结尾的字符串,但当您加密它以获取encrypted缓冲区时,它将是二进制缓冲区,strlen(加密),您传递给RSA_public_decrypt()将是无效。

所以改变

RSA_public_decrypt(strlen((char *)encrypted), encrypted, 
decrypted, rsa, RSA_PKCS1_PADDING);

RSA_public_decrypt(RSA_size(rsa), encrypted, 
decrypted, rsa, RSA_PKCS1_PADDING);