13

我在我的 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 或充气城堡中,无法获得 openssl 返回的确切身份验证标签,您能帮我解决这个问题吗?谢谢

4

1 回答 1

24

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

不幸的是,标签不必放在最后,它破坏了 GCM解密的在线性质——需要内部缓冲而不是能够直接返回明文。另一方面,在解密过程中会自动验证标签。

于 2014-10-14T20:54:10.420 回答