PHP使用OPENSSL RSA加密解密数据

加密数据有很多种方法,今天我们来看一下OPENSSL RSA的加密办法。

1、首先得安装php的openssl扩展

php -m | grep openssl

执行以上命令,确保已经安装了openssl php扩展

2、接下来要安装Linux openssl

yum -y install openssl-devel

3、生成RSA公钥和私钥

3.1、生成私钥

openssl genrsa 1024 > rsa_private.key

#注意:1024是密钥的长度,如果密钥较长,相应加密后的密文也会较长

3.2、生成公钥

openssl rsa -in rsa_private.key -pubout > rsa_public.key

4、PHP操作OPENSSL RSA加解密代码演示

//私钥加密
echo '<hr/>openssl encrypt';
$rsa_prikey = file_get_contents('~/rsa_private.key');
openssl_private_encrypt('test', $crypted, $rsa_prikey);
//$crypted 存储了加密后的内容
$rsa_pubkey = file_get_contents('~/rsa_public.key');
echo '<hr/>',$rsa_pubkey;
echo '<hr/>',$crypted;

//公钥解密
openssl_public_decrypt($crypted, $decrypted, $rsa_pubkey);
//$decrypted存储了解密后的内容
echo '<hr/>', $decrypted;

//还有私钥解密
openssl_private_decrypt($crypted, $decrypted, $rsa_prikey);
echo '<hr/>', $decrypted;

//还有公钥加密
openssl_public_encrypt('data here', $crypted, $rsa_pubkey);

5、使用场景

比如可以用在APP接口加密上使用,接口使用私钥将数据加密,APP中带有公钥文件,用公钥解密接口返回的加密数据