前後端對稱加密傳輸
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;
}
}
如果出現了以下情況
opensll_public_encrypt() :key parameter is not a valid public key in /www/xxxxxx.php on line 123
class Encrypt
{
public function publicEncrypt()
{
$password = "habx-2018";
$key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB";
$key_eol = (string) implode("\n", str_split((string) $key, 64));
$publicKey = (string) "-----BEGIN PUBLIC KEY-----\n" . $key_eol . "\n-----END PUBLIC KEY-----";
openssl_public_encrypt($password, $encryptData, $publicKey, OPENSSL_PKCS1_PADDING);
$encryptData = base64_encode($encryptData);
print_r("encryptData=============" . $encryptData);
return $encryptData;
}
}
(new Encrypt())->publicEncrypt();
使用
$key_eol = (string) implode("\n", str_split((string) $key, 64));
$publicKey = (string) "-----BEGIN PUBLIC KEY-----\n" . $key_eol . "\n-----END PUBLIC KEY-----";
把KEY按照64位增加一個 \n
的方式處理
CryptoJS
Git地址:https://github.com/brix/crypto-js
文件地址:https://code.google.com/archive/p/crypto-j...
注意:
明文長度沒有限制但是加密的文字也會隨之變長
這個庫也是與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);
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結