<?php
/**
* @description RSA公钥加密 私钥解密
* @param string $data 待加解密数据
* @param string $operate 操作类型 encode:加密 decode:解密
* @return string 返回加密内容/解密内容
*/
function RSA_openssl($data, $operate = 'encode') {
//RSA 公钥
$rsa_public = '此处填写公钥';
//RSA 私钥
$rsa_private = '此处填写私钥';
//RSA 公钥加密
if ('encode' == $operate) {
$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) {
return '公钥不可用';
}
$return_en = openssl_public_encrypt($data, $crypted, $key);
if (!$return_en) {
return '公钥加密失败';
}
return base64_encode($crypted);
}
//RSA 私钥解密
if ('decode' == $operate) {
$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) {
return '私钥不可用';
}
$return_de = openssl_private_decrypt(base64_decode($data), $decrypted, $key);
if (!$return_de) {
return '私钥解密失败';
}
return $decrypted;
}
return '';
}
?>