环境 php5.6
<?php
/**
* @class_name RSA加密类
*/
class Rsa
{
const KEY_LENGTH = 1024; // 长度,因RSA对明文加密长度有限制,所以采用分段加密。
private $__privateKey;
private $__publicKey;
// 使用这个类要传入公钥私钥路径
public function __construct($config)
{
if (!extension_loaded('openssl')) {
throw new Exception('缺少openssl模块');
}
if (empty($config['publicKey']) && empty($config['privateKey'])) {
throw new Exception('缺少公钥或私钥参数');
}
if (!empty($config['publicKey'])) {
$public_key = file_get_contents($config['publicKey']);
$this->__publicKey = openssl_pkey_get_public($public_key);
}
if (!empty($config['privateKey'])) {
$private_key = file_get_contents($config['privateKey']);
$this->__privateKey = openssl_pkey_get_private($private_key);
}
}
/**
* @name 加密
* @author wan.cheng
* @param array $originData 原数据
* @return string
*/
public function encrypt($originData)
{
$encryptData = ''; // 存储加密后的数据
$originData = json_encode($originData);
$partLength = self::KEY_LENGTH / 8 - 11; // 每块明文的长度
$parts = str_split($originData, $partLength); // 明文分块
foreach ($parts as $part) {
$encryptTemp = '';
openssl_public_encrypt($part, $encryptTemp, $this->__publicKey);
$encryptData .= $encryptTemp;
}
return base64_encode($encryptData);
}
/**
* @name 解密
* @author wan.cheng
* @param $encryptData 加密后的数据
* @return array
*/
public function decrypt($encryptData)
{
$originData = ''; // 存储解密后的数据
$encryptData = base64_decode($encryptData);
$partLength = self::KEY_LENGTH / 8; // 每块密文的长度
$parts = str_split($encryptData, $partLength); // 密文分块
foreach ($parts as $part) {
$encryptTemp = '';
openssl_private_decrypt($part, $encryptTemp, $this->__privateKey);
$originData .= $encryptTemp;
}
return json_decode($originData, true);
}
/**
* @name 非分段加密
* @author wan.cheng
* @param [string] @originData 需要加密的字符串
* @return str 加密后的字符串
*/
public function shortEncrypt($originData)
{
$encryptTemp = '';
openssl_public_encrypt($originData, $encryptTemp, $this->__publicKey);
return base64_encode($encryptTemp);
}
/**
* @name 非分段解密
* @author wan.cheng
* @param [string] $encryptData [加密的字符串]
* @return [type] [description]
*/
public function shortDecrypt($encryptData)
{
$encryptData = base64_decode($encryptData);
$encryptTemp = '';
openssl_private_decrypt($encryptData, $encryptTemp, $this->__privateKey);
return $encryptTemp;
}
}