【发布时间】:2020-10-14 19:00:31
【问题描述】:
我在网上有一个功能说这是 AES-256 位加密:
public static String encrypt(String strToEncrypt, String secret)
{
try
{
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
现在,这是使用 HMAC-SHA256。那么这实际上是 AES 还是散列?还是仅使用 HMAC 散列密钥?我的意思是 SHA-256 是一种散列算法? 此外,这听起来可能很基础,但 HMAC 是一种散列/加密吗?
【问题讨论】:
-
安全警告 - 此代码使用静态 IV 进行完全加密 UNSECURE。请使用随机 IV,请使用 GCM 模式进行身份验证。
-
这是我对基于密码的加密问题的回答的损坏副本。那里的评论应该回答您的问题以及恢复安全所需的部分并解释更好模式的选项等。
-
你的问题没有多大意义。 AES 提供机密性,SHA-256 通过散列提供密钥派生。它们一起构成了一个密码系统。除了密钥派生之外,还可以使用 HMAC-SHA-256 通过构建流式密码来进行加密(机密性),并且可以通过使用 CMAC 来使用 AES 进行真实性。然后他们将组成一个不同的密码系统。
-
我有一些examples。有用于密文认证的HMAC(完整性检查)
标签: java encryption aes