ublic static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws…
- User
ublic 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);
code// 提取实际的加密数据 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); }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});
code$("#_password").val(encrypted.toString()); return encrypted.toString(); }让js加密方式与解密方式一样 采用AES/GCM/NoPadding
- Assistant
为了使 JavaScript 中的加密方式与 Java 中的解密方式兼容,我们需要使用 AES GCM 模式进行加密。JavaScript 的 CryptoJS 库本身并不支持 GCM 模式,因此我们需要使用 Web Crypto API,它能够处理 AES GCM。
以下是如何使用 Web Crypto API 完成 AES GCM 加密的示例代码:
JavaScript 加密代码
javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.