我正在编写一个简单的应用程序来使用 AES / CBC(模式)加密我的消息。据我了解 CBC 模式需要 IV 参数,但我不知道为什么我的代码在不使用 IV 参数的情况下工作。任何人都可以解释为什么吗?谢谢。
加密消息无一例外地打印:T9KdWxVZ5xStaisXn6llfg==。
public class TestAES {
public static void main(String[] args) {
try {
byte[] salt = new byte[8];
new SecureRandom().nextBytes(salt);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec("myPassword".toCharArray(), salt, 100, 128);
SecretKey tmp = keyFactory.generateSecret(keySpec);
SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
enCipher.init(Cipher.ENCRYPT_MODE, key);
// enCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] cipherBytes = enCipher.doFinal("myMessage".getBytes());
String cipherMsg = BaseEncoding.base64().encode(cipherBytes);
System.out.println("Encrypted message: " + cipherMsg);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
当它在没有 IV 的情况下使用时,对于某些类型的密码(包括 AES),它隐式使用 0 IV。参见密码类文档.
空 IV(或确定性 IV)的缺点是它容易受到字典攻击。 IV 的要求是防止相同的明文块每次都产生相同的密文。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)