Created
May 24, 2017 02:54
-
-
Save dolphin836/c069c8aad7ddb33d8c16fa17f2a0ec7f to your computer and use it in GitHub Desktop.
[PHP RSA2 签名算法] #tags:签名,RSA2,算法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Rsa2 | |
{ | |
private static $PRIVATE_KEY = 'rsa_private_key.pem'; | |
private static $PUBLIC_KEY = 'rsa_public_key.pem'; | |
/** | |
* 获取私钥 | |
* @return bool|resource | |
*/ | |
private static function getPrivateKey() | |
{ | |
$privKey = self::$PRIVATE_KEY; | |
return openssl_pkey_get_private($privKey); | |
} | |
/** | |
* 获取公钥 | |
* @return bool|resource | |
*/ | |
private static function getPublicKey() | |
{ | |
$publicKey = self::$PUBLIC_KEY; | |
return openssl_pkey_get_public($publicKey); | |
} | |
/** | |
* 创建签名 | |
* @param string $data 数据 | |
* @return null|string | |
*/ | |
public function createSign($data = '') | |
{ | |
if (!is_string($data)) { | |
return null; | |
} | |
return openssl_sign( | |
$data, | |
$sign, | |
self::getPrivateKey(), | |
OPENSSL_ALGO_SHA256 | |
) ? base64_encode($sign) : null; | |
} | |
/** | |
* 验证签名 | |
* @param string $data 数据 | |
* @param string $sign 签名 | |
* @return bool | |
*/ | |
public function verifySign($data = '', $sign = '') | |
{ | |
if (!is_string($sign) || !is_string($sign)) { | |
return false; | |
} | |
return (bool)openssl_verify( | |
$data, | |
base64_decode($sign), | |
self::getPublicKey(), | |
OPENSSL_ALGO_SHA256 | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_once "Rsa2.php"; | |
$rsa2 = new Rsa2(); | |
$data = 'my data'; //待签名字符串 | |
$strSign = $rsa2->createSign($data); //生成签名 | |
var_dump($strSign); | |
$is_ok = $rsa2->verifySign($data, $sign); //验证签名 | |
var_dump($is_ok); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment