【发布时间】:2017-09-17 14:22:11
【问题描述】:
我使用this answer 中的示例代码用Java 编写了一个加密/解密原型。但是,我正在尝试使用 AES 的计数器模式 (CTR),加密值似乎与我尝试加密的整数序列一样可递增。
考虑我的原型的以下输出:
i = 0: enc='5941F8', dec='000', length=6
i = 1: enc='5941F9', dec='001', length=6
i = 2: enc='5941FA', dec='002', length=6
i = 3: enc='5941FB', dec='003', length=6
i = 4: enc='5941FC', dec='004', length=6
i = 5: enc='5941FD', dec='005', length=6
i = 6: enc='5941FE', dec='006', length=6
i = 7: enc='5941FF', dec='007', length=6
i = 8: enc='5941F0', dec='008', length=6
i = 9: enc='5941F1', dec='009', length=6
i = 10: enc='5940F8', dec='010', length=6
i = 11: enc='5940F9', dec='011', length=6
i = 12: enc='5940FA', dec='012', length=6
请注意enc 值通常与dec 值仅相差一个数字。 AES 计数器模式生成的加密值通常是可迭代的/彼此相似的还是我做错了什么?
到目前为止,我已经尝试过使用不同的加密密钥、初始化向量、填充方案、更长/更短的整数序列(从不同的值开始)等,但到目前为止似乎没有任何效果。此外,到目前为止,Google 和其他关于计数器模式下 Java AES 密码的 SO 问题几乎没有用处。请记住,我是加密新手。
我的原型代码如下:
public class Encryptor {
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
return DatatypeConverter.printHexBinary(encrypted);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] decrypted = cipher.doFinal(DatatypeConverter.parseHexBinary(encrypted));
return new String(decrypted);
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
System.out.println(decrypt(key, initVector,
encrypt(key, initVector, "Hello World")));
for (int i = 0; i < 1000; ++i) {
String encrypted = encrypt(key, initVector, StringUtils.leftPad("" + i, 3, '0'));
String decrypted = decrypt(key, initVector, encrypted);
int encLen = encrypted.length();
System.out.println("i = " + i + ": enc='" + encrypted + "', dec='" + decrypted + "', length=" + encLen);
}
}
}
【问题讨论】:
-
有趣的是,我对您链接的答案投了反对票。你也应该。在 CBC 模式下使用相同的 IV 是一个问题,但在 CTR 模式下这是一个更大的问题,因此您的问题。
-
请注意我在链接答案下的评论,这应该阻止您提出这个问题。我是否不够清楚应该做什么?
-
不,答案很好。当我接受你的建议时,我得到了更好的数据。但是你的回答提出了一个有趣的推论问题。请参阅下面对您的答案的评论。
标签: java encryption cryptography aes ctr-mode