/**
* RSA公钥加密
* @param string $string 待加解密数据
* @return string 返回加密内容
*/
public function rsa_public_encode($string){
try{
$rsa_public = '';
$public_key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($rsa_public, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
$key = openssl_pkey_get_public($public_key);
if(!$key){
throw new \Exception('公钥不可用');
}
$result = openssl_public_encrypt($string, $crypted, $key);
if(!$result){
throw new \Exception('公钥加密失败');
}
openssl_free_key($key);
return base64_encode($crypted);
}catch (\Exception $e){
$errorMsg = $e->getMessage() ? $e->getMessage() : 'encode error';
return '';
}
}
/**
* RSA公钥解密
* @param string $string 待解密数据
* @return string 返回解密内容
*/
public function rsa_public_decode($string){
try{
$rsa_public = '';
$public_key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($rsa_public, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
$key = openssl_pkey_get_public($public_key);
if(!$key){
throw new \Exception('公钥不可用');
}
$result = openssl_public_decrypt(base64_decode($string), $decrypted, $key);
openssl_free_key($key);
if(!$result){
throw new \Exception('公钥解密失败');
}
return $decrypted;
}catch (\Exception $e){
$errorMsg = $e->getMessage() ? $e->getMessage() : 'decode error';
return '';
}
}
/**
* RSA私钥解密
* @param string $string 待解密数据
* @return string 返回解密内容
*/
public function rsa_private_decode($string){
try{
$rsa_private = '';
$private_key = "-----BEGIN PRIVATE KEY-----\n" . wordwrap($rsa_private, 64, "\n", true) . "\n-----END PRIVATE KEY-----";
$key = openssl_pkey_get_private($private_key);
if(!$key){
throw new \Exception('私钥不可用');
}
$result = openssl_private_decrypt(base64_decode($string), $decrypted, $key);
if(!$result){
throw new \Exception('私钥解密失败');
}
return $decrypted;
}catch (\Exception $e){
$errorMsg = $e->getMessage() ? $e->getMessage() : 'decode error';
return '';
}
}
PHP RSA公钥加密解密
最新推荐文章于 2024-03-31 21:25:52 发布