AES-GCM: AEADBadTagException: mac check in GCM failed

你说的曾经没有我的故事 提交于 2019-12-04 10:26:17
Dakota Jay Whipple

I was having this same issue. For me, it had to do with encoding the string. I ended up doing:

  1. Get ASCII bytes from string you want to encrypt (UTF-8 in your case)
  2. Encrypt bytes
  3. Encode bytes in Base64 string

Then to decrypt string I did:

  1. Decode encrypted string to Base64 bytes
  2. Decrypt Base64 bytes
  3. Create new string using ASCII.

Here is the code :

private String encrypt(String src) {
    byte[] srcBytes = src.getBytes(StandardCharsets.US_ASCII);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);

    byte[] cipherText = cipher.doFinal(srcBytes);
    byte[] encryptedBytes = new byte[12 + cipherText.length];

    System.arraycopy(ivBytes, 0, encryptedBytes, 0, 12);
    System.arraycopy(cipherText, 0, encryptedBytes, 12, cipherText.length);

    return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}

private String decrypt(String encryptedString) {
    byte[] encryptedBytes = Base64.decode(encryptedString, Base64.DEFAULT);

    cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(128, encryptedBytes, 0, 12));
    byte[] decryptedBytes = cipher.doFinal(encryptedBytes, 12, encryptedBytes.length-12);

    return Base64.encodeToString(decryptedBytes, Base64.DEFAULT);
}

Any variables I didn't include how to initialize them can be inferred from the java docs. I was trying to do this in Android so I'm not sure how different it is. I found this post to be incredibly helpful: Java AES/GCM/NoPadding - What is cipher.getIV() giving me?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!