PHP 和 Web 端对称加密传输|JSEncrypt|CryptoJS

前后端对称加密传输

JSEncrypt

Git地址:https://github.com/travist/jsencrypt

首先这个包 需要提前生成 公钥 私钥 和 依赖 openssl

注意:

​ 明文长度最大为公钥长度-11,假如我的公钥长度是128,那明文最长也就117

​ 如果需要加密解密长文本,请看下一种前后端对称加解密方式

​ 这个库是与openssl一起工作。

如何使用这个库:

  • 在您的终端(基于Unix的操作系统)中输入以下内容。
openssl genrsa -out rsa_1024_priv.pem 1024
  • 这会生成一个私钥,您可以通过执行以下操作来看到...
cat rsa_1024_priv.pem
  • 然后,您可以将其复制并粘贴到index.html中的私钥部分。
  • 接下来,您可以通过执行以下命令获取公钥。
openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
  • 您可以通过键入...来查看公钥
cat rsa_1024_pub.pem

前端加密解密的写法如下:

<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="bin/jsencrypt.min.js"></script>
<script type="text/javascript">
$(function () {
    //被加密的信息
    var data = 'my message';

    //公钥
    var pub_key = '-----BEGIN PUBLIC KEY-----\n' +
        'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN\n' +
        'FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76\n' +
        'xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4\n' +
        'gwQco1KRMDSmXSMkDwIDAQAB\n' +
        '-----END PUBLIC KEY-----';

    //私钥
    var private_key = '-----BEGIN RSA PRIVATE KEY-----\n' +
        'MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ\n' +
        'WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR\n' +
        'aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB\n' +
        'AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv\n' +
        'xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH\n' +
        'm7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd\n' +
        '8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF\n' +
        'z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5\n' +
        'rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM\n' +
        'V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe\n' +
        'aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil\n' +
        'psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz\n' +
        'uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876\n' +
        '-----END RSA PRIVATE KEY-----';

    //new JSEncrypt
    var js_encrypt = new JSEncrypt();
    //初始化公钥
    js_encrypt.setPublicKey(pub_key);
    //初始化私钥
    js_encrypt.setPrivateKey(private_key);

    //通过 公钥 加密
    var encrypted = js_encrypt.encrypt(data);
    console.log(encrypted);

    //通过 私钥 解密
    var uncrypted = js_encrypt.decrypt(encrypted);
    console.log(uncrypted);
});
</script>

对应PHP后台加密解密的写法如下:

class Encrypt
{
    const JS_ENCRYPT = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN
FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76
xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4
gwQco1KRMDSmXSMkDwIDAQAB
-----END PUBLIC KEY-----';

    const JS_DECRYPT = '-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ
WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR
aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB
AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv
xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH
m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd
8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF
z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5
rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM
V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe
aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil
psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz
uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876
-----END RSA PRIVATE KEY-----';

    /**
     * 解密
     *
     * @param string $encryptString
     *
     * @return bool|string
     */
    public static function privateDecrypt($encryptString = '')
    {
        $decrypted  = '';
        $privateKey = self::JS_DECRYPT;
        openssl_private_decrypt(base64_decode($encryptString), $decrypted, $privateKey);

        return $decrypted;
    }

    /**
     * 加密
     *
     * @param string $data
     *
     * @return bool|string
     */
    public static function publicEncrypt($data = '')
    {
        $encrypt_data = '';
        openssl_public_encrypt($data, $encrypt_data, self::JS_ENCRYPT);
        $encrypt_data = base64_encode($encrypt_data);

        return $encrypt_data;
    }
}

CryptoJS

Git地址:https://github.com/brix/crypto-js

文档地址:https://code.google.com/archive/p/crypto-js/

注意:

​ 明文长度没有限制但是加密的文本也会随之变长

​ 这个库也是与openssl一起工作。

前端加密解密的写法如下:

<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://cdn.bootcss.com/crypto-js/3.1.9/crypto-js.js"></script>
<script>
const AES_KEY = "qq3217834abcdefg"; //16位
const AES_IV = "1234567890123456";  //16位

function aes_encrypt(plainText) {
    var encrypted = CryptoJS.AES.encrypt(plainText, CryptoJS.enc.Utf8.parse(AES_KEY), {iv:  CryptoJS.enc.Utf8.parse(AES_IV)});
    return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

function aes_decrypt(ciphertext) {
    var decrypted = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(AES_KEY), {iv: CryptoJS.enc.Utf8.parse(AES_IV)});
    return decrypted.toString(CryptoJS.enc.Utf8);
}

data = 'my message';
encrypt_data = aes_encrypt(data);
console.log(encrypt_data);
decrypt_data = aes_decrypt(encrypt_data);
console.log(decrypt_data);
</script>

对应PHP后台加密解密的写法如下:

class AesEncrypt
{
    const AES_KEY = "qq3217834abcdefg"; //16位
    const AES_IV  = "1234567890123456"; //16位

    public static function aes_decrypt($str)
    {
        $decrypted = openssl_decrypt(base64_decode($str), 'aes-128-cbc', self::AES_KEY, OPENSSL_RAW_DATA, self::AES_IV);

        return $decrypted;
    }

    public static function aes_encrypt($plain_text)
    {
        $encrypted_data = openssl_encrypt($plain_text, 'aes-128-cbc', self::AES_KEY, OPENSSL_RAW_DATA, self::AES_IV);

        return base64_encode($encrypted_data);
    }
}

本文章首发在 Laravel China 社区