1

我的任务是使用 AES/GCM 的特殊功能来验证 A 部分并加密单个数据块的 B 部分。我在使用 Java-8 实现解决方案时遇到问题。

以下示例使用 256 位的数据块。前 128 位应仅被验证。后面的 128 位应加密。组合操作的结果标签预计为 128 位。

我相信我能够实现一个只加密两个 128 位数据块的变体。

SecureRandom random = new SecureRandom();
byte[] initVector   = new BigInteger(96, random).toByteArray();
byte[] data         = new BigInteger(255, random).toByteArray();
byte[] key          = new BigInteger(255, random).toByteArray();
byte[] encrypted    = new byte[data.length];

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(16 * Byte.SIZE, initVector));
cipher.update(data, 0, data.length, encrypted, 0);
byte[] tag = cipher.doFinal();

任何人都可以提供有关如何修改代码以便仅对前 128 位数据进行身份验证的说明吗?

4

2 回答 2

4

您需要使用其中一种updateAAD方法

在您的情况下,是这样的(请注意,您需要在orupdateAAD电话之前拨打电话):updatedoFinal

cipher.updateAAD(data, 0, 128);              // first 128 bits are authenticated
cipher.update(data, 128, 128, encrypted, 0); // next 128 are encrypted
于 2017-01-20T21:30:46.880 回答
2

Matt 是对的,您需要使用updateAAD. 但是还有很多其他的错误。

例如,您不能只使用BigInteger来创建随机值。问题是对于某些值,左侧会有一个00附加值(用于编码无符号整数),有时不是。如果数字很小,它也可能生成太少的字节。

此外,在 Java 中,标签被认为是密文的一部分。在我看来,这是一个错误,它确实会损害功能。但目前情况就是这样。

一个更好的编程方法是这样的:

// --- create cipher
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

// --- generate new AES key
KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES");
aesKeyGen.init(256);
SecretKey aesKey = aesKeyGen.generateKey();

// --- generate IV and GCM parameters
SecureRandom random = new SecureRandom();
byte[] initVector   = new byte[96 / Byte.SIZE];
random.nextBytes(initVector);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initVector);
cipher.init(Cipher.ENCRYPT_MODE, aesKey,
        gcmParameterSpec);

// --- process any AAD (just a bunch of zero bytes in this example)
byte[] aad = new byte[128];
cipher.updateAAD(aad);

// --- process any data (just a bunch of zero bytes in this example)
byte[] data         = new byte[128];
// use cipher itself to create the right buffer size
byte[] encrypted    = new byte[cipher.getOutputSize(data.length)];
int updateSize = cipher.update(data, 0, data.length, encrypted, 0);
cipher.doFinal(encrypted, updateSize);

它以不同的方式生成所有参数,并通过Cipher实例动态确定输出缓冲区的大小。

于 2017-01-21T13:25:37.183 回答