后端加密
<?php
function encryptString($data, $key) {
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$result = base64_encode($iv . $encrypted);
return $result;
}
$key = "YourSecretKey"; // 替换为您自己的密钥
$data = "Hello, World!";
$encryptedData = encryptString($data, $key);
echo $encryptedData;
?>
前端解密:
crypto下载地址
https://registry.npmjs.org/crypto-js/-/crypto-js-3.1.2.tgz
前端代码
<script>
function decryptString(encryptedData, key) {
const rawData = CryptoJS.enc.Base64.parse(encryptedData);
const iv = CryptoJS.lib.WordArray.create(rawData.words.slice(0, 4));
const ciphertext = CryptoJS.lib.WordArray.create(rawData.words.slice(4));
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext },
CryptoJS.enc.Utf8.parse(key),
{ iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
);
return decrypted.toString(CryptoJS.enc.Utf8);
}
const key = "YourSecretKey";
const u = decryptString("后端加密后的字符串", key);
</script>