gpt4 book ai didi

java - Pycrypto AES GCM加密和Java解密

转载 作者:行者123 更新时间:2023-11-29 04:19:03 38 4
gpt4 key购买 nike

我正在使用 Pycryptodome(一个 PyCrypto 分支)来创建 AES-GCM 密文。我使用以下 Python 代码进行加密:

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 进行解密:

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 不会将散列标签添加到消息中 - 您必须将其附加到加密消息中:

例如

ciphertext, tag = cipher.encrypt_and_digest(message)
ciphertext = ciphertext + tag

关于java - Pycrypto AES GCM加密和Java解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50396221/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com