PHP对字符串进行RSA加密、解密的演示

最初发表于: 2020-01-08 17:23:10

代码如下

<?php

/**用公钥加密 
 *   @param  $str  待加密数据
 *   返回: 加密后的数据
 */
function encrypt($str)
{
    $public_key = openssl_pkey_get_public(RSA_PUBLIC);
    if (!$public_key) {
        die('公钥不可用');
    }

    //第一个参数是待加密的数据只能是string,第二个参数是加密后的数据,第三个参数是openssl_pkey_get_public返回的资源类型,第四个参数是填充方式
    $return_en = openssl_public_encrypt($str, $crypted, $public_key);
    if (!$return_en) {
        return ('加密失败,请检查RSA秘钥');
    }

    return base64_encode($crypted);
}


/**用私钥解密
 *   输入 @param $eb64 已经加密的数据
 *   输出 解密后的数据
 */
function decrypt($eb64)
{
    $private_key = openssl_pkey_get_private(RSA_PRIVATE);
    if (!$private_key) {
        die('私钥不可用');
    }

    $return_de = openssl_private_decrypt(base64_decode($eb64), $decrypted, $private_key);
    if (!$return_de) {
        return ('解密失败,请检查RSA秘钥');
    }

    return $decrypted;
}


/**主进程 */
function main()
{
    $str = "哈哈你好";
    echo '原数据是:';
    echo $str;
    echo '<br>';
    echo '加密后是: ';
    echo encrypt($str);
    echo '<hr>';

    $eb64 = 'Xps5qT9ALGws0HLZhWYeC/YG+93+eylpwZR/mK0+r4qEALQD7pZuu6oeVl4zJgi/9sL/HeyvrmN0pC2GYhr2wyY7Uvf/Z4DF/C70r8zXd12XlWqd0v937XNEsSCjocQ8u1rmwjaR0IdTk16jVuAuZlwGb4kBaNTqEJSuIspiZMo=';
    echo '待解密是:';
    echo $eb64;
    echo '<br>';
    echo '解密后是: ';
    echo decrypt($eb64);
}


/**开始 */
//RSA 公钥
define('RSA_PUBLIC', '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmkANmC849IOntYQQdSgLvMMGm
8V/u838ATHaoZwvweoYyd+/7Wx+bx5bdktJb46YbqS1vz3VRdXsyJIWhpNcmtKhY
inwcl83aLtzJeKsznppqMyAIseaKIeAm6tT8uttNkr2zOymL/PbMpByTQeEFlyy1
poLBwrol0F4USc+owwIDAQAB
-----END PUBLIC KEY-----');

//RSA 私钥
define('RSA_PRIVATE', '-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKaQA2YLzj0g6e1h
BB1KAu8wwabxX+7zfwBMdqhnC/B6hjJ37/tbH5vHlt2S0lvjphupLW/PdVF1ezIk
haGk1ya0qFiKfByXzdou3Ml4qzOemmozIAix5ooh4Cbq1Py6202SvbM7KYv89syk
HJNB4QWXLLWmgsHCuiXQXhRJz6jDAgMBAAECgYAIF5cSriAm+CJlVgFNKvtZg5Tk
93UhttLEwPJC3D7IQCuk6A7Qt2yhtOCvgyKVNEotrdp3RCz++CY0GXIkmE2bj7i0
fv5vT3kWvO9nImGhTBH6QlFDxc9+p3ukwsonnCshkSV9gmH5NB/yFoH1m8tck2Gm
BXDj+bBGUoKGWtQ7gQJBANR/jd5ZKf6unLsgpFUS/kNBgUa+EhVg2tfr9OMioWDv
MSqzG/sARQ2AbO00ytpkbAKxxKkObPYsn47MWsf5970CQQDIqRiGmCY5QDAaejW4
HbOcsSovoxTqu1scGc3Qd6GYvLHujKDoubZdXCVOYQUMEnCD5j7kdNxPbVzdzXll
9+p/AkEAu/34iXwCbgEWQWp4V5dNAD0kXGxs3SLpmNpztLn/YR1bNvZry5wKew5h
z1zEFX+AGsYgQJu1g/goVJGvwnj/VQJAOe6f9xPsTTEb8jkAU2S323BG1rQFsPNg
jY9hnWM8k2U/FbkiJ66eWPvmhWd7Vo3oUBxkYf7fMEtJuXu+JdNarwJAAwJK0YmO
LxP4U+gTrj7y/j/feArDqBukSngcDFnAKu1hsc68FJ/vT5iOC6S7YpRJkp8egj5o
pCcWaTO3GgC5Kg==
-----END PRIVATE KEY-----');

//触发主进程
main();