javax.crypto.AEADBadTagException: Tag mismatch!加密字符串时出错

2022-09-04 20:02:34

我为我的Android应用程序编写了一个简单的加密和解密帮助程序类,以安全地加密和存储字符串。

它由一个要加密的静态公共方法组成,然后调用一个私有静态方法来解密加密的消息并返回它。我以这种方式编写了该方法来检查消息在加密/解密后是否完好无损。

我用一个字符串编写了一个简单的JUnit测试,并在将字符串发送到Crypto加密方法之前和之后在字符串上调用了AssertEquals。

我在运行测试时收到以下错误:

javax.crypto.AEADBadTagException: Tag mismatch!

错误堆栈:

at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:571)
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1046)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:983)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:845)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at util.Crypto.decrypt(Crypto.java:94)
at util.Crypto.encrypt(Crypto.java:64)
at com.example.ali.meappley.CryptoTest.encryptAndDecryptTest(CryptoTest.java:29)

我是密码学的新手,但我阅读了不同的堆栈溢出回复,找不到任何帮助。一些用户建议在打电话之前打电话,但我无法设法让它工作。有什么建议吗?cipher.update(someByteArray)cipher.doFinal(someByteArray)

这是我的助手类

public class Crypto {

//public methods

//public static encrypt method
public static String encrypt(String messageToEncrypt, @Nullable byte[] associatedData) throws NoSuchPaddingException,
        NoSuchAlgorithmException,
        InvalidAlgorithmParameterException,
        InvalidKeyException,
        BadPaddingException,
        IllegalBlockSizeException {

    byte[] plainBytes = messageToEncrypt.getBytes();
/////////////////////////////////////////////////////////////////
    SecureRandom secureRandom = new SecureRandom();
    byte[] key = new byte[16];
    secureRandom.nextBytes(key);
    SecretKey secretKey = new SecretKeySpec(key, "AES");

    byte[] iv = new byte[12]; //NEVER REUSE THIS IV WITH SAME KEY
    secureRandom.nextBytes(iv);

    final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);

    if (associatedData != null) {
        cipher.updateAAD(associatedData);
    }

    byte[] cipherText = cipher.doFinal(plainBytes);

    ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + cipherText.length);
    byteBuffer.putInt(iv.length);
    byteBuffer.put(iv);
    byteBuffer.put(cipherText);
    byte[] cipherMessage = byteBuffer.array();

    Arrays.fill(key,(byte) 0); //overwrite the content of key with zeros
    ///////////////////////////////////////////////////////////////////

    byte[] decrypted = decrypt(cipherMessage, null, key);

    return decrypted.toString();
}

//public static decrypt method
private static byte[] decrypt(byte[] cipherMessage, @Nullable byte[] associatedData, byte[] key) throws NoSuchPaddingException,
        NoSuchAlgorithmException,
        InvalidAlgorithmParameterException,
        InvalidKeyException,
        BadPaddingException,
        IllegalBlockSizeException {

    ByteBuffer byteBuffer = ByteBuffer.wrap(cipherMessage);
    int ivLength = byteBuffer.getInt();
    if(ivLength < 12 || ivLength >= 16) { // check input parameter
        throw new IllegalArgumentException("invalid iv length");
    }
    byte[] iv = new byte[ivLength];
    byteBuffer.get(iv);
    byte[] cipherText = new byte[byteBuffer.remaining()];
    byteBuffer.get(cipherText);

    final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, iv));
    if (associatedData != null) {
        cipher.updateAAD(associatedData);
    }

    cipher.update(cipherText);
    byte[] plainText= cipher.doFinal(cipherText);

    return plainText;
}

答案 1

您的代码存在一些问题:

1)在您的加密方法中删除以下行(或将其移到解密调用后面)。

 Arrays.fill(key, (byte) 0); // overwrite the content of key with zeros

否则,用于加密和解密的密钥会有所不同。

2)在您的加密方法中,还会在解密调用中传递关联的数据,即替换

 byte[] decrypted = decrypt(cipherMessage, null, key);

 byte[] decrypted = decrypt(cipherMessage, associatedData, key);

为加密和解密传递的关联数据必须匹配有效性。对于相关数据,请参见例如 https://crypto.stackexchange.com/questions/6711/how-to-use-gcm-mode-and-associated-data-properly

3)在您的解密方法中删除行

 cipher.update(cipherText);

对于更新方法的目的,请参阅例如cipher.update在java中做什么?

所有这三个问题都产生了AEADBadTagException。

4)我怀疑出于测试目的,您的加密方法返回decrypted.toString(),但是它只为您提供对象的类和哈希码。例如,返回新的字符串(解密)会更有意义。


答案 2

推荐