无法使用openssl_private_decrypt解密任何消息

时间:2020-06-22 07:33:53

标签: php rsa php-openssl

我尝试使用 openssl_private_decrypt 函数从php解密RSA加密消息。但是该函数始终返回null。

我的功能如下:

function (){
    $encrypted = 'gu6F7PFj2t+Mchp2Vi8dpiEXXVDkrjrSoOnRlCWeZYjOL6WdjvxULyEG5j9dZPORNMYx5eB9gTdni4NYYCKW3GTGS0zaKGgadChy/KZAUo40sBVmTFN3YOT6FfEr4oXZ9c0DqSRJ/LrZsZvsiHh52LleA9sapOgsm0bsgWzgnnE=';
    $privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCMeu1UGlPod+yC/cD+qDWRyotkKly7A+gD+twgekiTguZUJPJl
ZnB2JpL/cU9oO9nOKn6WJ4DGy7qNjuOj7sLvIkgekPjW6RA2LgOgmS9gSKeOb1OI
i59QdoyNv6xOblPz7ihsc5g/KsKEVCLeP5RfBXRXEzS0KHbBnQ3zS8PktwIDAQAB
AoGASZJ7xyc+uKpOCNCDChvoamFsnVn+VMeX9LWmIbBJYFAW9wyeknKTBZ3wMK4U
S1/FE094GoW30OWT311tZUa/ehtKA0M9ODCk/Sx9eWxq/oR1e6ypJS8zzKG47DD3
3+PxKGh+IPJXo8qINvxj7yYbjMxydo8xvBufuBgjoaU9r7ECQQDcsOZIuhvhyWkf
fJFjmyFYPNJD8eJBQZnxk9uIH/yDl5vJ+bf7fNFc3t+Epnjqfgf98W5frLUeYuzT
reusJHF5AkEAovS9EowcIeMp3Ce1utSdGZpjAkGdwVwnxhDLnyO2/TuKNpYODOS7
/bLS3NCg9Kw6UF1VLltFwjsBcSoyDmMrrwJAQOMOQlHeAsvaSbSxdqzU6AGx/OIw
mOk13w6PHH3zG6nG12LB0oKHeBvbckAUCzYVGXgT8LNx6UZCxZY8Vbe9WQJAZbTq
7VCVnnDyB36hZmKdSwWZFiduFuk1yeFhtYnNBHDM6xTs4A9DZizefwOX8h4sp0wZ
hj1hZMD/PWpgo6ox8QJAFYMky0FT8n19mNRN9aGkQ2GDqO+F8jLEnFJMPXJMGyCg
85CGeRH9sF69skcNToZMR304Ms/xyfLeG72SksHT7g==
-----END RSA PRIVATE KEY-----';
    return openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);
}

解密后的内容如下: Salut les amis

1 个答案:

答案 0 :(得分:0)

您可以稍微修改代码以检测错误

function (){

    $encrypted = 'gu6F7PFj2t+Mchp2Vi8dpiEXXVDkrjrSoOnRlCWeZYjOL6WdjvxULyEG5j9dZPORNMYx5eB9gTdni4NYYCKW3GTGS0zaKGgadChy/KZAUo40sBVmTFN3YOT6FfEr4oXZ9c0DqSRJ/LrZsZvsiHh52LleA9sapOgsm0bsgWzgnnE=';
    $privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCMeu1UGlPod+yC/cD+qDWRyotkKly7A+gD+twgekiTguZUJPJl
ZnB2JpL/cU9oO9nOKn6WJ4DGy7qNjuOj7sLvIkgekPjW6RA2LgOgmS9gSKeOb1OI
i59QdoyNv6xOblPz7ihsc5g/KsKEVCLeP5RfBXRXEzS0KHbBnQ3zS8PktwIDAQAB
AoGASZJ7xyc+uKpOCNCDChvoamFsnVn+VMeX9LWmIbBJYFAW9wyeknKTBZ3wMK4U
S1/FE094GoW30OWT311tZUa/ehtKA0M9ODCk/Sx9eWxq/oR1e6ypJS8zzKG47DD3
3+PxKGh+IPJXo8qINvxj7yYbjMxydo8xvBufuBgjoaU9r7ECQQDcsOZIuhvhyWkf
fJFjmyFYPNJD8eJBQZnxk9uIH/yDl5vJ+bf7fNFc3t+Epnjqfgf98W5frLUeYuzT
reusJHF5AkEAovS9EowcIeMp3Ce1utSdGZpjAkGdwVwnxhDLnyO2/TuKNpYODOS7
/bLS3NCg9Kw6UF1VLltFwjsBcSoyDmMrrwJAQOMOQlHeAsvaSbSxdqzU6AGx/OIw
mOk13w6PHH3zG6nG12LB0oKHeBvbckAUCzYVGXgT8LNx6UZCxZY8Vbe9WQJAZbTq
7VCVnnDyB36hZmKdSwWZFiduFuk1yeFhtYnNBHDM6xTs4A9DZizefwOX8h4sp0wZ
hj1hZMD/PWpgo6ox8QJAFYMky0FT8n19mNRN9aGkQ2GDqO+F8jLEnFJMPXJMGyCg
85CGeRH9sF69skcNToZMR304Ms/xyfLeG72SksHT7g==
-----END RSA PRIVATE KEY-----';

    if (!openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey)) {
        throw new Exception(openssl_error_string());
    }
    return $decrypted;
}

我的机器上的结果是:

PHP Fatal error:  Uncaught Exception: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error in /home/foobar/test.php:20

因此,解码加密的字符串时会出现“ pkcs解码错误”。而且您的openssl_private_decrypt无法解密您的消息。请检查您对文本进行加密/ base64_encode的方式,以查看是否有任何错误。