/**
* @param string/array $data [待加密的字符串或者是数组]
* @uses rsa公钥加密
*/
private function rsaPublicEncrypt($data = '')
{
if (is_array($data)) {
$formatData = json_encode($data, JSON_UNESCAPED_UNICODE);
} else {
$formatData = $data;
}
//三方rsa公钥文件路径
$publicKeyPath = $this->config['rsaKey'] . 'tongchengjieqian.pub.key';
$keyContent = @file_get_contents($publicKeyPath);
$formatKey = $this->rsaPubKey($keyContent);
$publicKey = openssl_pkey_get_public($formatKey);
$publicLength = openssl_pkey_get_details($publicKey)['bits'];
$encrypted = '';
$part_len = $publicLength / 8 - 11;
$parts = str_split($formatData, $part_len);
foreach ($parts as $part) {
$encrypted_temp = '';
openssl_public_encrypt($part, $encrypted_temp, $publicKey);
$encrypted .= $encrypted_temp;
}
return $this->dataBase64Encode($encrypted);
}
/**
* @param $rsaPubKeyStr
* @return string
* @uses rsa公钥处理
*/
private function rsaPubKey($rsaPubKeyStr)
{
$base64 = str_replace(array('-', '_'), array('+', '/'), $rsaPubKeyStr);
$strKey = (wordwrap($base64, 64, PHP_EOL, true)) . PHP_EOL;
return "-----BEGIN PUBLIC KEY-----" . PHP_EOL . $strKey . "-----END PUBLIC KEY-----" . PHP_EOL;
}
/**
* @param $data
* @return string|string[]
* @uses urlBase64加码处理
*/
private function dataBase64Encode($data)
{
return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($data));
}
/**
* @param json $data [转换为json后的待签名数据]
* @uses 数据加签
*/
private function rsaSign($data)
{
//己方rsa私钥文件路径
$privateKeyPath = $this->config['rsaKey'] . 'ryt.pri.key';
$privateContent = @file_get_contents($privateKeyPath);
$privateKey = openssl_pkey_get_private($privateContent);
openssl_sign($data, $sign, $privateKey, self::RSA_ALGORITHM_SIGN_TYPE);
return $this->dataBase64Encode($sign);
}
/**
* @param json $decryptData [同步返回解密后的json数据]
* @param string $signature [同步返回的签名]
* @return int 0 || 1 [1:验签成功 0:验签失败]
* @uses 数据验签
*/
private function verifySign($decryptData, $signature)
{
//三方rsa公钥文件路径
$publicKeyPath = $this->config['rsaKey'] . 'tongchengjieqian.pub.key';
$keyContent = @file_get_contents($publicKeyPath);
$formatKey = $this->rsaPubKey($keyContent);
$publicKey = openssl_pkey_get_public($formatKey);
$sign = $this->dataBase64Decode($signature);
$result = openssl_verify($decryptData, $sign, $publicKey, self::RSA_ALGORITHM_SIGN_TYPE);
return $result;
}
/**
* @param $data
* @return false|string
* @uses urlBase64解码处理
*/
private function dataBase64Decode($data)
{
$base_64 = str_replace(array('-', '_'), array('+', '/'), $data);
return base64_decode($base_64);
}
目录
/**
* @return string $uniqid [唯一流水号]
* @uses 生成请求流水号
*/
private function generateNumber()
{
$uniqid = substr(uniqid(), 5, 8) . '-' . rand(1000, 9999) . '-' . substr(uniqid(), 9, 4) . '-' . rand(1000, 9999) . '-' . $this->getRandKey(2);
return $uniqid;
}
本文详细介绍了使用RSA算法进行数据加密、签名及验证的过程。包括公钥加密、私钥签名、数据分段加密、Base64编码解码、随机流水号生成等关键步骤。
1628

被折叠的 条评论
为什么被折叠?



