发布网友 发布时间:2022-04-22 01:36
共1个回答
热心网友 时间:2023-06-23 13:43
<?php
namespace libs;
class Rsa{
private static $PRIVATE_KEY;
private static $PUBLIC_KEY;
function __construct($pubKey = '', $privKey = '') {
self::$PUBLIC_KEY = $pubKey;
self::$PRIVATE_KEY = $privKey;
}
public static function urlsafeBDecode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base_decode(strtr($input, '-_', '+/'));
}
public static function urlsafeBEncode($input)
{
return str_replace('=', '', strtr(base_encode($input), '+/', '-_'));
}
private static function getPrivateKey(){
$privKey = self::$PRIVATE_KEY;
return openssl_pkey_get_private($privKey);
}
private static function getPublicKey(){
$pubKey = self::$PUBLIC_KEY;
return openssl_pkey_get_public($pubKey);
}
public static function privEncrypt($data)
{
if(!is_string($data)){
return null;
}
return openssl_private_encrypt($data,$encrypted,self::getPrivateKey())? self::urlsafeBEncode($encrypted) : null;
}
public static function privDecrypt($encrypted)
{
if(!is_string($encrypted)){
return null;
}
return (openssl_private_decrypt(self::urlsafeBDecode($encrypted), $decrypted, self::getPrivateKey()))? $decrypted : null;
}
public static function pubEncrypt($data)
{
if(!is_string($data)){
return null;
}
return openssl_public_encrypt($data,$encrypted,self::getPublicKey())? self::urlsafeBEncode($encrypted) : null;
}
public static function pubDecrypt($encrypted)
{
if(!is_string($encrypted)){
return null;
}
return (openssl_public_decrypt(self::urlsafeBDecode($encrypted), $decrypted, self::getPublicKey()))? $decrypted : null;
}
}
?>