我需要用密码加密一些数据。它必须是具有 256 位 key 的 AES 的变体。 我在网上搜索了一段时间,想出了这两个算法。现在我不知道该选择哪个,因为我不知道哪个是“救星”。
第一个是 PBEWithSHA256And256BitAES-CBC-BC:
public static byte[] encrypt(String plainText, char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 2048);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC", "BC");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher encryptionCipher = Cipher.getInstance("PBEWithSHA256And256BitAES-CBC-BC", "BC");
encryptionCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
return encryptionCipher.doFinal(plainText.getBytes());
}
另一个使用 PBEWithSHA256And256BitAES-CBC-BC 生成 key ,但使用 AES 加密:
public static byte[] encrypt(String plainText, char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC", "BC");
KeySpec spec = new PBEKeySpec(password, salt, 2048, 256);
SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText.getBytes());
}
那么,哪一个 - 为什么 - 更安全?它们之间有什么区别?
最佳答案
您当然应该为您的分组密码指定一种操作模式。这是 BC 实现中密码的“CBC”部分。否则,您将默认为 ECB 模式,该模式有可能进行简单的密码本重放攻击!所以,长话短说 - 不要使用底部的代码片段,更喜欢顶部的代码片段。
它可以通过指定操作模式和其他参数来修复,以类似于 BC 实现的方式运行 - 但老实说,如果你不知道这些东西,就使用 BC - 他们已经完成了工作和那些提供商已准备好“开箱即用”。
关于java - AES 与 PBEWithSHA256And256BitAES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30107048/