Pycrypto AES GCM加密和Java解密 [英] Pycrypto AES GCM encryption and Java decryption
本文介绍了Pycrypto AES GCM加密和Java解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Pycryptodome(PyCrypto分支)创建AES-GCM密文.我使用以下Python代码进行加密:
I'm using Pycryptodome (a PyCrypto fork) to create AES-GCM ciphertexts. I use the following Python code to encrypt:
cek = os.urandom(16)
nonce = os.urandom(12)
cipher = AES.new(cek, AES.MODE_GCM, nonce=nonce, mac_len=16)
ciphertext = cipher.encrypt(message)
然后我将其传递给Java进行解密:
I then pass this to Java to decrypt:
byte[] nonce = new byte[12];
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(cek, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(nonce);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmSpec);
byte[] decBytes = mCipher.doFinal(cipherText);
但是,出现以下错误:
Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:524)
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1023)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
推荐答案
您遗漏了一件事:Pycryptodome不会将哈希标签添加到邮件中-您必须将其附加到加密邮件中:
You're missing one thing: Pycryptodome does not add the hash tag to the message - you have to append it to the encrypted message:
例如
ciphertext, tag = cipher.encrypt_and_digest(message)
ciphertext = ciphertext + tag
这篇关于Pycrypto AES GCM加密和Java解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文