public static byte[] aesEncryptToBytes(String content, String encryptKey) throws…
- User
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { // Generate a random IV, GCM recommends 12 bytes for the IV byte[] iv = new byte[12]; SecureRandom random = new SecureRandom(); random.nextBytes(iv);
code// Prepare the secret key SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), "AES"); // Initialize the cipher for encryption Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, iv); // 128-bit authentication tag length cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec); // Encrypt the data byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); // Combine the IV and encrypted data for storage/transmission byte[] combined = new byte[iv.length + encrypted.length]; System.arraycopy(iv, 0, combined, 0, iv.length); System.arraycopy(encrypted, 0, combined, iv.length, encrypted.length); return combined; }这个是一个加密的方法
我这里有一个对应的解密方法 解密报错 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);
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); } - Assistant
- User
麻烦说中文
- Assistant
报错信息
javax.crypto.AEADBadTagException: Tag mismatch!通常意味着在使用 AES/GCM 模式进行解密时遇到了认证失败的问题。这可能由以下几种原因引起:-
密钥或 IV(初始向量)不匹配:请确保解密时使用的密钥和向量与加密时使用的一致。
-
数据损坏:检查加密数据在存储或传输过程中是否被改动或破坏。
-
数据处理不当:检查字节数组在处理过程中是否出现截断或非预期的修改。
以下是一些检查和故障排除的建议:
-
确保密钥和 IV 一致:验证解密密钥(
decryptKey)与加密密钥(encryptKey)完全相同。确保在解密时没有修改或使用不同的密钥或 IV。 -
字符编码一致性:确保所有字符串到字节数组的编码转换都是一致的,尤其是在处理密钥时。
-