編碼的世界 / 優質文選 / 文明

php openssl rsa 加密解密應用


2021年7月05日
-   

php openssl rsa 加密解密應用
 
1、安裝opensslyum -y install openssl-devel
2、安裝php openssl到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
3、生成公鑰和私鑰生成私鑰: openssl genrsa 1024 > private.key
(注意,1024是密鑰的長度,如果密鑰較長,相應加密後的密文也會較長)
生成公鑰: openssl rsa -in private.key -pubout > public.key
 
4、利用php加密和解密文本,代碼如下:
<?php
class mycrypt {
public $pubkey;
public $privkey;
function __construct() {
$this->pubkey = file_get_contents('/home/openssl/public.key');
$this->privkey = file_get_contents('/home/openssl/private.key');
}
public function encrypt($data) {
if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
public function decrypt($data) {
if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
$data = $decrypted;
else
$data = '';
return $data;
}
}
$rsa = new mycrypt();
echo $rsa -> encrypt('abc');
//echo $rsa -> decrypt('W+ducpssNJlyp2XYE08wwokHfT0bm87yBz9vviZbfjAGsy/U9Ns9FIed684lWjYyyofi/1YWrU0Mp8vLOYi8l6CfklBY=');

熱門文章