我使用此答案中的示例代码用 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 Cipher 的 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);
}
}
}