php openssl rsa 加密解密应用
首先关于安装openssl。参考安装xdebug的类似。
到php源码包的目录 ext/openssl 下执行:
/data/apps/php/bin/phpize
./configure --with-openssl --with-php-config=/data/apps/php/bin/php-config
make make install(可能需要mv config0.m4 config.m4)
把生成的 openssl.so 文件添加到php.ini中
extension = /xxx/openssl.so;
可以用以下命令查看安装的模块:
php -m |grep openssl
另外对于添加公钥私钥:
----------------------------------------------------------------
1.打开Terminal--cd 到指定文件夹MyTestCert
kenMac:~ MyTestCert$openssl
2.genrsa -out rsa_private_key.pem 2048
生成私钥。接下来Terminal显示内容如下:
3. pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM –nocrypt
把RSA私钥转换成PKCS8格式。提示输入密码,密码为空(直接回车)就行
4.rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
命令生成公钥。
关于加密的使用
-----封装加密部分----
pubkey = file_get_contents('/Applications/MAMP/bin/php/php7.1.0/rsa_public_key.pem'); $this->privkey = file_get_contents('/Applications/MAMP/bin/php/php7.1.0/rsa_private_key.pem'); } public function desEncode($data) { if (openssl_public_encrypt($data, $encrypted, $this->pubkey)) $data = base64_encode($encrypted); else throw new ErrorException('Unable to encrypt data. Perhaps it is bigger than the key size?'); return $data; } public function desDecode($data) { if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey)) $data = $decrypted; else $data = ''; return $data; }}
----加密的使用-----
public function actionOut() { //加密 $d = new DesOpenssl(); $data = $d->desEncode('data={"key":"11111"}'); echo $data; //解密 $d = new DesOpenssl(); $data = $d->desDecode("ugK2lblZxK9xpYpw0mwBgbIMI3ghhLyRuYrUkGiVLmVUildo4cCM52RNcxpKQFIzO3Shubatsxn98RPGm6CChE2EjIb+GdKUMB3ItfiVYAtBFW1mSubwU4bS3iQqCGz9i8spbZyINQvGtOn91MWTK7UrOoGoe54SrArRJLAidRK+g8aABChBADY6Lj7nSlRoko8GhpT/5oHwAil4gnFrgiiGX/UxEjP4WQv7qw/12yR/vCUAHjV+5bLMLesrFSVjFQbzTpzaX+XnMLouzXHQTpWrTaWL6UOfhDWD9NSOjPXWbTccpEg1UDpGbbj9cGzSRI1fWygK6B4e+Lvi/BV8+Q=="); echo $data; }