console
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CryptoJS AES Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
</head>
<body>
<h1>CryptoJS AES 加密解密示例</h1>
<div>
<label for="textToEncrypt">输入要加密的文本:</label><br>
<input type="text" id="textToEncrypt" value="word1 word2 word3" style="width: 80%;"><br><br>
<button onclick="runEncryption(1)">解密</button>
<button onclick="runEncryption(2)">加密</button>
</div>
<h3>结果:</h3>
<div id="results"></div>
<script>
const key = CryptoJS.enc.Utf8.parse("alvispasswordcj6");
const iv = CryptoJS.enc.Utf8.parse("initvaterialcjla");
function encryptText(plainText) {
const encrypted = CryptoJS.AES.encrypt(plainText, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
function decryptText(encryptedText) {
const decrypted = CryptoJS.AES.decrypt(encryptedText, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return CryptoJS.enc.Utf8.stringify(decrypted);
}
function runEncryption(type) {
const textToEncrypt = document.getElementById("textToEncrypt").value;
let encryptedText
let decryptedText
if(type === 1) {
encryptedText = encryptText(textToEncrypt);
console.log("加密后:", encryptedText);
}
if(type === 2) {
decryptedText = decryptText(textToEncrypt);
console.log("解密后:", decryptedText);
}
document.getElementById("results").innerHTML = `
<p><strong>原文:</strong>${textToEncrypt}</p>
<p><strong>加密后:</strong>${encryptedText}</p>
<p><strong>解密后:</strong>${decryptedText}</p>
`;
}
</script>
</body>
</html>