<?php
/*
* 公钥加密,私钥解密
* 私钥加签,公钥验签
*/
class Ga
{
const RSA_ENCRYPT_BLOCK_SIZE = 245;//117;//加密切割长度
const RSA_DECRYPT_BLOCK_SIZE = 256;//128;//解密切割长度
public $gy = 'xxx.cer';//公钥
public $sy = 'xxx.pfx';//私钥
public $sy_pwd='xxx';//私钥密码
//加密
public function encrypt_new($content)
{
$path=storage_path($this->gy);
$certificate = file_get_contents($path);
$key = openssl_pkey_get_public($certificate);
$result='';
$data = str_split($content, self::RSA_ENCRYPT_BLOCK_SIZE);
foreach ($data as $block) {
openssl_public_encrypt($block, $dataEncrypt, $key, OPENSSL_PKCS1_PADDING);
$result .= $dataEncrypt;
}
return $result ? base64_encode($result) : null;
}
//解密
public function decrypt_new($string)
{
$file_path=storage_path($this->sy);
$certs = array();
openssl_pkcs12_read(file_get_contents($file_path), $certs, $this->sy_pwd);
$encrypted = base64_decode($string);
//分段解密
$result = '';
$data = str_split($encrypted, self::RSA_DECRYPT_BLOCK_SIZE);
foreach ($data as $block) {
openssl_private_decrypt($block, $decrypted, $certs['pkey'],OPENSSL_PKCS1_PADDING);
$result .= $decrypted;
}
return $result ? $result : null;
}
//加签
public function sign_new($encrypted)
{
$file_path = storage_path($this->sy);
$certs = array();
openssl_pkcs12_read(file_get_contents($file_path), $certs,$this->sy_pwd);
$signature = '';
$result = openssl_sign($encrypted, $signature, $certs['pkey'], OPENSSL_ALGO_SHA256);
if (!$result) {
return false;
}
return base64_encode($signature);
}
//验签
public function verify($data,$sign)
{
$cert_path = storage_path($this->gy);
$source = openssl_pkey_get_public(file_get_contents($cert_path));
$res=openssl_verify($data, $sign, $source,OPENSSL_ALGO_SHA256); // 1:验签通过,0:验签失败,-1:系统内部错误
return $res;
}
}
```
php 公钥加密,私钥解密 & 私钥加签,公钥验签
最新推荐文章于 2025-05-31 19:58:53 发布