【发布时间】:2019-01-14 12:47:41
【问题描述】:
我的一位同事让我检查他的代码是否足够安全。我看到了一些这样的代码sn-p:
private static byte[] encrypt(String plain, String key) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(key.getBytes());
kg.init(128, secureRandom);
SecretKey secretKey = kg.generateKey();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plain.getBytes());
}
@Test
public void lcg() throws Throwable {
String plain = "abc";
String key = "helloworld";
byte[] c1 = encrypt(plain, key);
byte[] c2 = encrypt(plain, key);
Assert.assertArrayEquals(c1, c2);
}
这个encrypt函数用来加密敏感数据,加密后的数据会存入数据库。我认为它首先不起作用,因为 SecureRandom 不会两次生成相同的随机数,即使是由相同的种子初始化,但它只是在测试中起作用。
我认为以这种方式加密某些东西是不安全的,但我不知道这段代码 sn-p 有什么问题。
我的问题:
-
encrypt函数安全吗? - 如果不安全,这样做有什么问题?
【问题讨论】:
-
以这种方式使用 SecureRandom 已被弃用且不可移植。正如您所注意到的,它甚至可能不会连续两次生成相同的值。事实上,当前和过去的实现 生成了相同的值,因此导致这种反模式激增。而是使用正确的基于密码的 KDF,例如 PBKDF2。
-
"如果不安全,这样做有什么问题?"呃,对不起,我不明白这部分问题。什么问题?做什么?
-
不,它不安全。最后它是一个存储在你的程序中的静态密钥,只是有点混淆了。
-
@Robert
lcg方法被@Test注释的事实让我认为这个应用程序不一定使用静态键。
标签: java security cryptography