openssl
Posted hanling
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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----- " . $secret_key . "-----END PUBLIC KEY----- ";
} else if ($type == ‘pri‘) {
$pem_key = "-----BEGIN RSA PRIVATE KEY----- " . $secret_key . "-----END RSA PRIVATE KEY----- ";
} else {
echo(‘公私钥类型非法‘);
exit();
}
return $pem_key;
}
以上是关于openssl的主要内容,如果未能解决你的问题,请参考以下文章