【发布时间】:2014-01-20 05:59:08
【问题描述】:
我正在编写一个简单的应用程序来使用 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();
}
}
}
【问题讨论】:
-
之所以有效,是因为 Java 选择了一个随机 IV。您可以在初始化后使用
enCipher.getIV()来查看值(并将它们发送到另一端)。 -
doridori.github.io/Android-Security-Beware-of-the-default-IV 当您使用
AES/CBC/PKCS5Padding时,它可能使用的是旧的AndroidOpenSSL实现,(遗憾的是)默认为[0]IV
标签: java aes password-encryption cbc-mode