0

I've been trying to do AES_GCM encryption in Python and decryption in Java, below is the relevant code snippet for what I'm trying to accomplish, I have also checked the question at: Pycrypto AES GCM encryption and Java decryption this is similar to my problem. I am suspecting that the IV/nonce I set for Python is incorrect, any help would be greatly appreciated.

Python Encryption Code:

from Crypto.Cipher import AES
from base64 import b64encode
someKey = 'Sixteen byte key'
cipher = AES.new(someKey, AES.MODE_GCM, nonce='0000000000000000', mac_len=16)
ciphertext, tag = cipher.encrypt_and_digest(data)
ciphertext = ciphertext + tag
print b64encode(ciphertext)

Java Decryption Code:

private static byte[] initializationVector = new byte[16];


Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 
 
SecretKeySpec keySpec = new SecretKeySpec(someKey, "AES"); 

GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);  
     
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);

byte[] bytesString = Base64.getDecoder().decode(theString);  
 
return new String(cipher.doFinal(bytesString), "UTF-8");

I am however unable to decrypt this in Java, I get the following error:

javax.crypto.AEADBadTagException: Tag mismatch!
at java.base/com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:623)
at java.base/com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1116)
at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1053)
at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)
BlueHam
  • 37
  • 4
  • 2
    In the Python code the ciphertext is not Base64 encoded, whereas in the Java code it's Base64 decoded. Also, for a 0x00 value in the IV `\0` must be used instead of `0`, i.e. the IVs in both codes are currently different. In practice, GCM applies usually a 12 bytes IV, and the IV must not be static, of course. – Topaco Oct 21 '20 at 10:04
  • Thanks for your input, edited the post for the Base64 encoding for the Python snippet (I have it in my original code). Do you mean that for every `0` it should be `\0`? – BlueHam Oct 21 '20 at 10:38
  • 1
    Yep, `nonce=b'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'` would correspond to the IV used in Java code. – Topaco Oct 21 '20 at 10:40
  • Thank you, your answer in another question (https://stackoverflow.com/questions/58814261/how-to-encrypt-message-using-java-then-decrypt-message-using-python-for-aes-gcm) and your answer here helped me solve my problem. Cheers! – BlueHam Oct 21 '20 at 12:01
  • @BlueHam please paste the working code here. – Raisul Feb 28 '22 at 15:11

0 Answers0