openssl

const PRIVATE_KEY_PATH = '/home/work/tool/openssl-keys/private_key.pfx';//私钥
const PUBLIC_KEY_PATH = '/home/work/tool/openssl-keys/public_key.cer';//公钥

/**
* RSA最大加密明文大小
*/
const MAX_ENCRYPT_BLOCK = 117;

/**
* RSA最大解密密文大小
*/
const MAX_DECRYPT_BLOCK = 128;

/**
* @param string $data
* @return mixed
*/
public static function publicEncrypt($data = "")
{
 $keyFile = file_get_contents(self::PUBLIC_KEY_PATH);
 $public_key = openssl_pkey_get_public(self::format_secret_key($keyFile, 'pub'));

 $data = base64_encode(json_encode($data, JSON_FORCE_OBJECT));
 $data = str_split($data, self::MAX_ENCRYPT_BLOCK);
 $encrypted = '';
foreach($data as & $chunk){
 if(!openssl_public_encrypt($chunk, $encryptData, $public_key)){
 return '';
 }else{
 $encrypted .= $encryptData;
 }
}
 return base64_encode($encrypted);
}

/**
* @param string $data
* @return mixed
*/
public static function privateEncrypt($data = "")
{
 // 初始化商户私钥
 $privateKeyFile = file_get_contents(SELF::PRIVATE_KEY_PATH);
 $private_key = openssl_pkey_get_private(self::format_secret_key($privateKeyFile, 'pri'));
 $data = str_split(base64_decode($data), self::MAX_DECRYPT_BLOCK);
 $decrypted = '';
foreach($data as & $chunk){
 if(!openssl_private_decrypt($chunk, $decryptData, $private_key)){
 return '';
 }else{
 $decrypted .= $decryptData;
 }
}
 return base64_decode($decrypted);
}

/**
* 将字符串格式公私钥格式化为pem格式公私钥
* @param $secret_key
* @param $type
* @return string
*/
private static function format_secret_key($secret_key, $type)
{
 // 添加pem格式头和尾
 if ($type == 'pub') {
 $pem_key = "-----BEGIN PUBLIC KEY-----\n" . $secret_key . "-----END PUBLIC KEY-----\n";
 } else if ($type == 'pri') {
 $pem_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $secret_key . "-----END RSA PRIVATE KEY-----\n";
 } else {
 echo('公私钥类型非法');
exit();
 }
 return $pem_key;
}
posted @ 2020-03-04 18:30  玲汐  阅读(381)  评论(0编辑  收藏  举报