RSA2.php类
<?php
namespace RSA2;
class RSA2
{
/**********生成私钥**********/
public function makeRSA2Key($len = 1024){
$arr = [];
//创建公钥和私钥
$res = openssl_pkey_new(array('private_key_bits' => $len)); #此处必须不能包含引号。
//提取私钥
openssl_pkey_export($res, $private_key);
//生成公钥
$public_key = openssl_pkey_get_details($res);
$public_key = $public_key["key"];
$arr['private_key'] = $private_key;
$arr['public_key'] = $public_key;
return $arr;
}
/**********私钥格式化**********/
public function formatPriKey($priKey) {
$fKey = "-----BEGIN PRIVATE KEY-----\n";
$len = strlen($priKey);
for($i = 0; $i < $len; ) {
$fKey = $fKey . substr($priKey, $i, 64) . "\n";
$i += 64;
}
$fKey .= "-----END PRIVATE KEY-----";
return $fKey;
}
/**********公钥格式化**********/
function formatPubKey($pubKey) {
$fKey = "-----BEGIN PUBLIC KEY-----\n";
$len = strlen($pubKey);
for($i = 0; $i < $len; ) {
$fKey = $fKey . substr($pubKey, $i, 64) . "\n";
$i += 64;
}
$fKey .= "-----END PUBLIC KEY-----";
return $fKey;
}
/**
* 生成签名
* @param string $signString 待签名字符串
* @param [type] $priKey 私钥
* @return string base64结果值
*/
function getSign($signString,$priKey){
$privKeyId = openssl_pkey_get_private($priKey);
$signature = '';
openssl_sign($signString, $signature, $privKeyId);
openssl_free_key($privKeyId);
return base64_encode($signature);
}
/**
* 校验签名