码迷,mamicode.com
首页 > 其他好文 > 详细

openssl

时间:2020-03-04 19:01:27      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:home   code   lock   orm   hunk   foreach   amp   格式   cti   

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;
}

openssl

标签:home   code   lock   orm   hunk   foreach   amp   格式   cti   

原文地址:https://www.cnblogs.com/hanling/p/12411318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!