我的任务是使用 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 位数据进行身份验证吗?
使用updateAAD
方法之一。
在您的情况下,如下所示(请注意,您需要在update
或doFinal
调用之前进行updateAAD
调用):
cipher.updateAAD(data, 0, 128); // first 128 bits are authenticated
cipher.update(data, 128, 128, encrypted, 0); // next 128 are encrypted
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
实例动态确定输出缓冲区的大小。