gpt4 book ai didi

java - 在 Java 中使用身份验证标签的 AES GCM 实现

转载 作者:可可西里 更新时间:2023-11-01 04:38:57 27 4
gpt4 key购买 nike

我在我的 android 项目中使用 AES GCM 身份验证,它工作正常。但是当它与 openssl API 生成标签比较时,认证标签会出现一些问题。请在下面找到java代码:

SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte[] iv = generateRandomIV();
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
int outputLength = cipher.getOutputSize(data.length); // Prepare output buffer
byte[] output = new byte[outputLength];
int outputOffset = cipher.update(data, 0, data.length, output, 0);// Produce cipher text
outputOffset += cipher.doFinal(output, outputOffset);

我在 iOS 中使用 openssl 并使用以下代码生成身份验证标签

NSMutableData* tag = [NSMutableData dataWithLength:tagSize];
EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_GET_TAG, [tag length], [tag mutableBytes])

在 java 或 bouncy caSTLe 中,无法获得 openssl 返回的确切身份验证标签,你能帮我解决这个问题吗?谢谢

最佳答案

在 Java 中,不幸的是在密文末尾添加了标签。您可以使用 GCMParameterSpec 配置大小(以位为单位,使用 8 的倍数)——否则默认为 128 位的完整大小。因此,如果您确实需要,可以使用 Arrays.copyOfRange(ciphertext, ciphertext.length - (tagSize/Byte.SIZE), ciphertext.length) 获取标签。

不幸的是,标签没有放在末尾,它扰乱了 GCM 的在线性质解密 - 需要内部缓冲而不是能够直接返回明文。另一方面,标签在解密过程中会自动验证。

关于java - 在 Java 中使用身份验证标签的 AES GCM 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23864440/

27 4 0