有乎-价值、共享、信任

What you care about-value, sharing, trust

PHP里RSA加密解密传输数据

| 阅读:2303 发表时间:2020-03-25 23:51:11 技术专栏

第1步:定义private_key和public_key (可以自行找工具生成):

这里从网上找了对应的key

define('RSA_PUBLIC', '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNS084xZA0cbdjsZxO7nWalECT
rho2vzt4KjE2dVCmDLOLAEHs7nCrJQmZ9Zu4WJe1HdC4TeHaXu0uc7aHdnX8mWHA
9wBasPQXSzK5g6MqRrrDLj0xskJhN0oPalyMCfPfDj95aycdw5jMjEz/e7K29tR4
4I8d+bt9uNc+iEj4DwIDAQAB
-----END PUBLIC KEY-----');
 
 
define('RSA_PRIVATE','-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDNS084xZA0cbdjsZxO7nWalECTrho2vzt4KjE2dVCmDLOLAEHs
7nCrJQmZ9Zu4WJe1HdC4TeHaXu0uc7aHdnX8mWHA9wBasPQXSzK5g6MqRrrDLj0x
skJhN0oPalyMCfPfDj95aycdw5jMjEz/e7K29tR44I8d+bt9uNc+iEj4DwIDAQAB
AoGBAMF4EYbNGONzr4JyZX41V/t/b4Q9dVLW0XKjQJGz6XczTRjX+0kQRHnlg7Dm
OAR46S+0k3i9XPVwtFEsl339852SAnkVAgo/2+cRLG/XZqAoSCMOOrta/LZVxS94
Wu5iyVt6WPxDcCrKAkpQAQEqRFgq0PspS5rSrDtkVMWG5Q6xAkEA+yI4VG8m1GHt
HGsC8Aqb64yzgSbJRXl72Ifr2wxsmJi0A5oZin1VGDLqWWvznisAUpB9jB8ANf+u
0+bB6L3KXQJBANFFsmbRPJucW4UJ2H/bE3JQ1w3/R+WG1BExHmfI/p2zJcl6LoJy
Ze+tZAzhjjO0njLBcwSgxwSfW2WyfuEjnVsCQQDNYlkrRJQ/Ea93lFUct7B43eNY
dr4Y4ZfVqKPNy8Vsr0ZZw8erqYDUf5+FbnIZIxXqcF0dIaVshCUZDBn+HGnJAkEA
wFa4kzs34yWgD/RuoYRuqSCXp2u7Xr++5VYpxeW77qEa18SOPqJ6AgFw9U3RbsBQ
rgGSfuxuPldgn2Wgq7gaBQJAXrHAnLP7MVCRfYMABxdOncg+C+PO0nkwos09eAic
Y9zqqB1JvxVxdx3E5LquULtf4l6POwrTt8P+Oy6dGvDHqw==
-----END RSA PRIVATE KEY-----');
第2步:使用封装好的加解密方法 


public function RAS_openssl($data,$type='encode'){
 
		if (empty($data)) {
		    return 'data参数不能为空';
		}
	 
		//私钥解密
		if ($type=='decode') {
		    $private_key = openssl_pkey_get_private(RSA_PRIVATE);
			if (!$private_key) {
			    return('私钥不可用');
			}
			$return_de = openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
			if (!$return_de) {
			    return('解密失败,请检查RSA秘钥');
			}
			return urldecode($decrypted);
		}
	 
		//公钥加密
		$key = openssl_pkey_get_public(RSA_PUBLIC);
		if (!$key) {
		    return('公钥不可用');
		}
		$return_en = openssl_public_encrypt($data, $crypted, $key);
		if (!$return_en) {
		    return('加密失败,请检查RSA秘钥');
		}
		return base64_encode($crypted);
	}

注意:RSA加密是有长度限制的,加密长的字符经过base64,无法正常解密。

建议:只用于加密特殊的Key

*文章为作者独立观点,不代表【uuuho有乎】的立场
本文由【uuuho有乎】发表并编辑,转载此文章须经作者同意,并请附上出处及本页链接。如有侵权,请联系本站删除。

Who are we?