public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws…
- User
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { // GCM 的推荐 IV 长度为 12 字节 byte[] iv = new byte[12]; System.arraycopy(encryptBytes, 0, iv, 0, iv.length);
// 提取实际的加密数据 byte[] encryptedBytes = new byte[encryptBytes.length - iv.length]; System.arraycopy(encryptBytes, iv.length, encryptedBytes, 0, encryptedBytes.length);
// 准备密钥 SecretKeySpec secretKeySpec = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), “AES”);
// 使用 AES/GCM 模式解密 Cipher cipher = Cipher.getInstance(“AES/GCM/NoPadding”); GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); // 128 位认证标签
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, parameterSpec);
// 解密数据 byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, StandardCharsets.UTF_8); } 这个是java的解密
function go() { var pwd =$("#pwd").val(); var key = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12"); var srcs = CryptoJS.enc.Utf8.parse(pwd); var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
$("#_password").val(encrypted.toString()); return encrypted.toString(); }这个是js的加密 能否把加密方式改成跟解密的方式一致
- Assistant
要使 JavaScript 的加密方式与 Java 的解密方式一致,需要在 JavaScript 中使用与 Java 解密代码相同的 AES-GCM 方案。以下是一种方法,使用
crypto模块,这种方法只支持在 Node.js 环境中运行:const crypto = require('crypto'); function encrypt(text, key) { // 将密钥转换为 Buffer const keyBuffer = Buffer.from(key, 'utf-8'); // 推荐使用 12 字节作为 IV const iv = crypto.randomBytes(12); // 创建 AES-GCM 加密器 const cipher = crypto.createCipheriv('aes-128-gcm', keyBuffer, iv, { authTagLength: 16 }); // 加密文本并获取加密数据 let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); // 获取认证标签 const authTag = cipher.getAuthTag().toString('hex'); // 返回包含 IV,认证标签和加密数据的结果 return { iv: iv.toString('hex'), encryptedData: encrypted, authTag: authTag }; } function go() { const pwd = $("#pwd").val(); const key = "abcdefgabcdefg12"; // 16-byte key for AES-128 const encryptedData = encrypt(pwd, key); // 输出结果格式:iv:encryptedData:authTag const result = `${encryptedData.iv}:${encryptedData.encryptedData}:${encryptedData.authTag}`; $("#_password").val(result); return result; }