php 的rsa加密与解密

WBOY
Release: 2016-06-20 12:47:45
Original
1003 people have browsed it

系统:centos6.5

linux系统生成公私钥对方法:

openssl genrsa -out rsa_private_key.pem 1024
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
第一条命令生成原始 RSA私钥文件 rsa_private_key.pem,第二条命令将原始 RSA私钥转换为 pkcs8格式,第三条生成RSA公钥 rsa_public_key.pem

下面是代码:

公钥加密私钥解密

        $source='abcde';        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_public_key.pem', 'r');        $res = openssl_get_publickey($pkeyid);        openssl_public_encrypt($source,$crypttext,$res);        echo $crypttext;        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_private_key.pem', 'r');        $res2 = openssl_get_privatekey($pkeyid);        if(openssl_private_decrypt($crypttext,$data,$res2)){            echo $data;        }else{            echo "false";        }
Copy after login

私钥加密公钥解密

$source='abcde';        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_private_key.pem', 'r');        $res = openssl_get_privatekey($pkeyid);        openssl_private_encrypt($source,$crypttext,$res);        echo $crypttext;        $pkeyid=file_get_contents(DIR_BASE.'/rsa_key/rsa_public_key.pem', 'r');        $res2 = openssl_get_publickey($pkeyid);        if(openssl_public_decrypt($crypttext,$data,$res2)){            echo $data;        }else{            echo "false";        }
Copy after login



 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!