【发布时间】:2018-06-30 06:07:49
【问题描述】:
我一直在尝试使用 AES 比较加密模式,并注意到我的 CFB 输出与我的 CTR 输出相同。我做错了什么还是应该发生这种情况?我的 CTR 加密函数与下面的 CFB 函数相同,只是将“AES/CTR/NoPadding”字符串作为 Cipher.getInstance() 的参数。谢谢!
try {
// Dernier exemple CTR mode
// Clé 16 bits
byte[] keyBytes = new byte[]{(byte) 0x36, (byte) 0xf1, (byte) 0x83,
(byte) 0x57, (byte) 0xbe, (byte) 0x4d, (byte) 0xbd,
(byte) 0x77, (byte) 0xf0, (byte) 0x50, (byte) 0x51,
(byte) 0x5c, 0x73, (byte) 0xfc, (byte) 0xf9, (byte) 0xf2};
// IV 16 bits (préfixe du cipherText)
byte[] ivBytes = new byte[]{(byte) 0x69, (byte) 0xdd, (byte) 0xa8,
(byte) 0x45, (byte) 0x5c, (byte) 0x7d, (byte) 0xd4,
(byte) 0x25, (byte) 0x4b, (byte) 0xf3, (byte) 0x53,
(byte) 0xb7, (byte) 0x73, (byte) 0x30, (byte) 0x4e, (byte) 0xec};
// Initialisation
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// Mode
Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
String originalText = "hello i am original";
// ///////////////////////////////ENCRYPTING
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
ciphered = cipher.doFinal(originalText.getBytes());
String cipherText = new String(ciphered, "UTF-8");
System.out.println("ciphered: " + cipherText);
// ///////////////////////////////DECRYPTING
cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE , key, ivSpec);
byte[] plain = cipher.doFinal(ciphered);
originalText = new String(plain, "UTF-8");
System.out.println("plaintext: " + originalText);
}
catch (Exception e){
}
【问题讨论】:
-
尝试加密多个块,看看它们是否仍然相同。如果您只加密单个块,它们基本上是相同的。您确实有 CFB 模式的填充,这是一个区别。不要理会
new String(ciphered, "UTF-8");,这没有任何意义。如果你想可视化它,你可能应该对输出进行十六进制编码。 Base64 也是一种选择。 -
@JamesKPolk 成功了!谢谢大佬
标签: java encryption cryptography