<?phpnamespaceApp\Helpers;classRSATools{private$privateKey;private$publicKey;private$type;publicfunction__construct(){$thi...
<?php
namespace App\Helpers;
class RSATools
{
private $privateKey;
private $publicKey;
private $type;
public function __construct()
{
$this->setType('RSA');
}
public function setPrivatekey($key)
{
if(!file_exists($key)){
exit("PrivateKey File Lost");
}
$this->privateKey = file_get_contents($key);
return $this;
}
public function setPublicKey($key){
if(!file_exists($key)){
exit("PublicKey File Lost");
}
$this->publicKey=file_get_contents($key);
return $this;
}
public function setType($type='RSA'){
$this->type=$type;
return $this;
}
public function sign($content)
{
if(!$this->privateKey){
exit("PrivateKey Not Found!");
}
$signature = null;
if ($this->type == 'RSA') {
openssl_sign($content, $signature, $this->privateKey, OPENSSL_ALGO_SHA1);
} elseif ($this->type == 'RSA2') {
openssl_sign($content, $signature, $this->privateKey, OPENSSL_ALGO_SHA256);
}
return $signature ? base64_encode($signature) : null;
}
public function verify($content, $signature)
{
$signature = str_replace(" ", "+", $signature);
$content = str_replace(" ", "+", $content);
if(!$this->publicKey){
exit("PublicKey Not Found!");
}
$verify = false;
if ($this->type == 'RSA') {
$verify = openssl_verify($content, base64_decode($signature), $this->publicKey, OPENSSL_ALGO_SHA1);
} elseif ($this->type == 'RSA2') {
$verify = openssl_verify($content, base64_decode($signature), $this->publicKey, OPENSSL_ALGO_SHA256);
}
return (boolean)$verify;
}
public function encrypt($content)
{
if(!$this->publicKey){
exit("publicKey Not Found!");
}
$encrypted = null;
if ($this->type == 'RSA') {
openssl_public_encrypt($content, $encrypted, $this->publicKey, OPENSSL_ALGO_SHA1);
} elseif ($this->type == 'RSA2') {
openssl_public_encrypt($content, $encrypted, $this->publicKey, OPENSSL_ALGO_SHA256);
}
return base64_encode($encrypted);
}
public function decrypt($content)
{
$content = str_replace(" ", "+", $content);
if(!$this->privateKey){
exit("PrivateKey Not Found!");
}
$decrypted = null;
if ($this->type == 'RSA') {
openssl_private_decrypt(base64_decode($content), $decrypted, $this->privateKey, OPENSSL_ALGO_SHA1);
} elseif ($this->type == 'RSA2') {
openssl_private_decrypt(base64_decode($content), $decrypted, $this->privateKey, OPENSSL_ALGO_SHA256);
}
return $decrypted;
}
}全文详见:http://xpxw.com/?id=154