function check(originalData){
// 生成随机的对称加密密钥
const encryptionKey = CryptoJS.lib.WordArray.random(32).toString(); // 256位密钥
console.log('密钥', encryptionKey)
// 使用对称加密密钥对数据进行加密
let encryptedData = encrypt(originalData, encryptionKey);
console.log('生成的加密编码:', encryptedData)
// 向服务器发送加密后的数据
const serverRes = server(encryptedData, encryptionKey);
console.log('服务器返回', serverRes)
if (serverRes) {
console.log(originalData, '输入正确')
return true
} else {
console.log('输入错误')
return false
}
}
function server(encryptedData,encryptionKey) {
console.log('收到来自用户的加密数据:', encryptedData)
const userKey = '123456'
// 模拟服务器处理,直接返回加密数据
return userKey === decrypt(encryptedData,encryptionKey);
}
function encrypt(data, encryptionKey) {
return CryptoJS.AES.encrypt(data, encryptionKey).toString();
}
function decrypt(encryptedData, encryptionKey) {
let decryptedBytes = CryptoJS.AES.decrypt(encryptedData, encryptionKey);
return decryptedBytes.toString(CryptoJS.enc.Utf8);
}
前端 使用 crypto 对称加密 demo
最新推荐文章于 2024-07-17 20:19:26 发布