代码语言:javascript复制
<?php
/**
* Created by PhpStorm.
* User: zhangHong
* Date: 2019/7/18
* Time: 9:54
*/
namespace appcommoncontroller;
class Encryption {
private $publicKey;
private $privateKey;
private $keyLength;
/**
* 初始化
*
*/
public function __construct(){
$this->publicKey = Config("encryption")['rsa']['publicKey'];
$this->privateKey = Config("encryption")['rsa']['privateKey'];
// 公钥
$publicId = openssl_pkey_get_public($this->publicKey);
$this->keyLength = openssl_pkey_get_details($publicId)['bits'];
// 私钥
$privateId = openssl_pkey_get_private($this->privateKey);
$this->keyLength = openssl_pkey_get_details($privateId)['bits'];
}
/**
* 生成签名
*
* @param string 签名材料
* @param string 签名编码(base64/hex/bin)
* @return 签名值
*/
public function sign($data, $code = 'base64'){
$ret = false;
$privateId = openssl_get_privatekey($this->privateKey);
if (openssl_sign($data, $ret, $privateId)){
$ret = $this->encodeSign($ret, $code);
}
return $ret;
}
/**
* 验证签名
*
* @param string 签名材料
* @param string 签名值
* @param string 签名编码(base64/hex/bin)
* @return bool
*/
public function verify($data, $sign, $code = 'base64'){
$ret = false;
$sign = $this->decodeSign($sign, $code);
if ($sign !== false) {
$publicId = openssl_get_publickey($this->publicKey);
switch (openssl_verify($data, $sign, $publicId)){
case 1: $ret = true; break;
case 0:
case -1:
default: $ret = false;
}
}
return $ret;
}
/**
* 加密
*
* @param string 明文
* @param string 密文编码(base64/hex/bin)
* @param int 填充方式(貌似php有bug,所以目前仅支持OPENSSL_PKCS1_PADDING)
* @return string 密文
*/
public function encrypt($data, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING){
$ret = false;
if (!$this->checkPadding($padding, 'en')) $this->errorInfo('padding error');
if (openssl_public_encrypt($data, $result, $this->publicKey, $padding)){
$ret = $this->encodeSign($result, $code);
}
return $ret;
}
/**
* 解密
*
* @param string 密文
* @param string 密文编码(base64/hex/bin)
* @param int 填充方式(OPENSSL_PKCS1_PADDING / OPENSSL_NO_PADDING)
* @param bool 是否翻转明文(When passing Microsoft CryptoAPI-generated RSA cyphertext, revert the bytes in the block)
* @return string 明文
*/
public function decrypt($data, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING, $rev = false){
$ret = false;
$data = $this->decodeSign($data, $code);
if (!$this->checkPadding($padding, 'de')) $this->errorInfo('padding error');
if ($data !== false){
if (openssl_private_decrypt($data, $result, $this->privateKey, $padding)){
$ret = $rev ? rtrim(strrev($result), "