将NodeJS AES-256-CBC解密代码转换为Java实现
NodeJS AES-256-CBC解密代码转Java实现
直接给你转好的Java代码,完全对齐原NodeJS的逻辑,注释里标了对应原代码的步骤:
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESDecryptor { public static String decrypt(String someAuthString) throws Exception { // 对应NodeJS:密钥做SHA256哈希,原代码slice(0,32)多余(SHA256本身就是32字节),要对齐可加Arrays.copyOf(encKey,32) String encKeyStr = "0Z8ZUcy1Qh8lnt199MTwTPEe2g1E2tE3"; MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); byte[] encKey = sha256.digest(encKeyStr.getBytes(StandardCharsets.UTF_8)); // 对应NodeJS:生成16个全0的IV byte[] iv = new byte[16]; // 对应NodeJS:初始化AES-256-CBC解密器,用NoPadding因为要手动处理填充 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(encKey, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); // 对应NodeJS:Base64解码密文→解密→转UTF8字符串 byte[] encryptedBytes = Base64.getDecoder().decode(someAuthString); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); // 对应NodeJS:自定义PKCS5填充移除逻辑 return removePKCS5Padding(decryptedText); } private static String removePKCS5Padding(String text) { if (text.isEmpty()) { return text; } // 取最后一个字符的ASCII值当填充长度 int padLength = text.charAt(text.length() - 1); String paddedText = text.substring(0, text.length() - padLength); // 截取后为空就返回原文本,否则返回截取结果 return paddedText.isEmpty() ? text : paddedText; } // 测试用,替换成你的加密字符串就行 public static void main(String[] args) throws Exception { String testEncryptedStr = "你的Base64加密字符串"; System.out.println(decrypt(testEncryptedStr)); } }
关键逻辑对齐说明:
- 密钥哈希:Java的
MessageDigest和NodeJS的crypto.createHash完全等价,SHA256输出固定32字节,原代码的slice(0,32)可以省略,要严格对齐的话加一行encKey = Arrays.copyOf(encKey, 32)即可。 - 全零IV:Java创建16字节数组默认就是全0,和NodeJS拼接16个空字符效果一致。
- 解密模式:必须用
NoPadding,因为原代码是手动移除填充,用内置PKCS5Padding会重复处理导致错误。 - 填充移除:完全复刻原NodeJS的逻辑,取最后一个字符的ASCII值作为填充长度,截取对应部分,空值判断也和原代码一致。
内容的提问来源于stack exchange,提问作者alice menon
相关产品推荐
相关产品推荐

