openssl RSA非对称加密解密

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了openssl RSA非对称加密解密相关的知识,希望对你有一定的参考价值。

需要先了解的openssl系列函数

  • openssl_pkey_get_private 从证书中解析获取私钥,以供使用。成功,返回真实的密钥资源标识符(Resource ID),否则返回false
  • openssl_pkey_get_public 从证书中解析获取公钥,以供使用。成功,返回真实的密钥资源标识符(Resource ID),否则返回false
  • openssl_private_encrypt($data, $encrypted, $privateKeyResourceID, OPENSSL_PKCS1_PADDING)
  • //使用私钥key加密数据data并且将结果保存至变量crypted中
  • openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKeyResourceID, OPENSSL_PKCS1_PADDING)
  • //私钥加密的内容通过公钥可用解密出来
<?php
/**
 * Created by PhpStorm.
 * User: zrj
 * Date: 18-11-7
 * Time: 上午10:22
 */
declare(strict_types=1);//开启强类型模式

//私匙
$privateKeyString = <<<EOF
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAxHS1H/9uMS+waaP8vkEHx0EJWqPnRjYIzHKrXeMQ3fjZmxPG
MJmzwKVdADQlaFbA/NePu7dVFyzFo2yrAFlJD9bWs6of79OM2QGxu/AL2GqwjaOZ
/+5tSkxqU8fj+/sb35U9kGxy/k4KPwlatTaHIkXb7qebCGX1hgNw2BkRrNfXWRX+
EVs8Oy/I/d1CMQMF3mvsCFvoUAE/UJVOOAjjQ6rBX+PorWXuTIKgWgSFWwzsRWJN
hQo6P6Y/amx2Jb6Nr0rHIJIREICdYMAp2DSC+uU+jl85NqT3U89BRRG+58feoUOL
DGiv0hRQ7+k1e47MfiwKpCpJOkldEJjywMhl1QIDAQABAoIBAHBQuOyeQAVm2ljL
JEgxLZ1BFXP4mNSPN+CK/mYi1xXQm7gJShmnBhlxcQYYyfoo/xSOuOH9ImypcCTK
j8kXQqoHjaAR90hJjhDS4yYrStpjxKR1kCm9ykXcAj373d/F5F2jGRtkpSm2vCzl
0DIiBogVoHOE5yGaCRChDva8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EY-----
EOF;

//公匙
$publicKeyString = <<<EOF
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxHS1H/9uMS+waaP8vkEH
x0EJWqPnRjYIzHKrXeMQ3fjZmxPGMJmzwKVdADQlaFbA/NePu7dVFyzFo2yrAFlJ
D9bWs6of79OM2QGxu/AL2GqwjaOZ/+5tSkxqU8fj+/sb35U9kGxy/k4KPwlatTaH
IkXb7qebCGX1hgNw2BkRrNfXWRX+EVs8Oy/I/d1CMQMF3mvsCFvoUAE/UJVOOAjj
Q6rBX+PorWXuTIKgWgSFWwzsRWJNhQo6P6Y/amx2Jb6Nr0rHIJIREICdYMAp2DSC
+uU+jl85NqT3U89BRRG+58feoUOLDGiv0hRQ7+k1e47MfiwKpCpJOkldEJjywMhl
1QIDAQAB
-----END PUBLIC KEY-----
EOF;

$data = "helloworld";

try {
    //从证书中解析获取私钥。成功,返回真实的密钥资源标识符
    $privateKeyResourceID = openssl_pkey_get_private($privateKeyString);
    if ($privateKeyResourceID === false) throw new Exception(‘private key string is wrong‘);

    //从证书中解析获取公钥,以供使用。成功,返回真实的密钥资源标识符
    $publicKeyResourceID = openssl_pkey_get_public($publicKeyString);//这个函数可用来判断公钥是否是可用的
    if ($publicKeyResourceID === false) throw new Exception(‘public key string is wrong‘);

    //使用私钥key加密数据data并且将结果保存至变量crypted中。
    //加密后的数据可以通过openssl_public_decrypt()函数来解密。
    openssl_private_encrypt($data, $encrypted, $privateKeyResourceID, OPENSSL_PKCS1_PADDING);

    //私钥加密
    $encrypted = base64_encode($encrypted);//加密之后的结果,base64只是为了避免特殊字符

    openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKeyResourceID, OPENSSL_PKCS1_PADDING);//私钥加密的内容通过公钥可用解密出来

    echo $decrypted . PHP_EOL;

} catch (Exception $e) {
    die($e->getMessage());
}

以上是关于openssl RSA非对称加密解密的主要内容,如果未能解决你的问题,请参考以下文章

使用OpenSSL进行RSA非对称加密(C++版本)

使用OpenSSL进行RSA非对称加密(C++版本)

openssl 非对称加密算法RSA命令详解

openssl RSA非对称加密解密

PHP基于openssl实现的非对称加密操作

非对称加密算法之RSA介绍及OpenSSL中RSA常用函数使用举例