如何使用 PBKDF2 在 Java 中安全地散列密码?
如何在 Java 中安全地对密码进行哈希处理
在任何处理敏感用户信息的应用程序中,保护密码至关重要。散列密码提供了一种单向加密方法,可防止密码被解密并以纯文本形式存储。
场景:
您想要散列密码以存储在数据库,添加随机盐以增加
解决方案:
Java 运行时环境 (JRE) 包含使用 PBKDF2(基于密码的密钥派生函数 2)进行密码散列的内置工具。此方法提供了强大的密码保护,具体实现方法如下:
SecureRandom random = new SecureRandom(); byte[] salt = new byte[16]; random.nextBytes(salt); KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 128); SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] hash = f.generateSecret(spec).getEncoded(); Base64.Encoder enc = Base64.getEncoder(); System.out.printf("salt: %s%n", enc.encodeToString(salt)); System.out.printf("hash: %s%n", enc.encodeToString(hash));
PBKDF2 采用密码、随机盐和成本参数来计算哈希。成本参数控制散列的计算强度,成本越高,散列速度越慢,但安全性更强。
要进一步增强安全性,请考虑使用像这样的实用程序类:
import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.Base64; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; /** * Utility class for PBKDF2 password authentication */ public final class PasswordAuthentication { // Constants public static final String ID = "$"; public static final int DEFAULT_COST = 16; private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; private static final int SIZE = 128; private static final Pattern layout = Pattern.compile("\\$(\d\d?)\$(.{43})"); // Instance variables private final SecureRandom random; private final int cost; /** * Constructor with default cost */ public PasswordAuthentication() { this(DEFAULT_COST); } /** * Constructor with specified cost * * @param cost the exponential computational cost of hashing a password, 0 to 30 */ public PasswordAuthentication(int cost) { iterations(cost); // Validate cost this.cost = cost; this.random = new SecureRandom(); } private static int iterations(int cost) { if ((cost < 0) || (cost > 30)) { throw new IllegalArgumentException("cost: " + cost); } return 1 << cost; } /** * Hash a password for storage * * @return a secure authentication token to be stored for later authentication */ public String hash(char[] password) { byte[] salt = new byte[SIZE / 8]; random.nextBytes(salt); byte[] dk = pbkdf2(password, salt, 1 << cost); byte[] hash = new byte[salt.length + dk.length]; System.arraycopy(salt, 0, hash, 0, salt.length); System.arraycopy(dk, 0, hash, salt.length, dk.length); Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); return ID + cost + '$' + enc.encodeToString(hash); } /** * Authenticate with a password and a stored password token * * @return true if the password and token match */ public boolean authenticate(char[] password, String token) { Matcher m = layout.matcher(token); if (!m.matches()) { throw new IllegalArgumentException("Invalid token format"); } int iterations = iterations(Integer.parseInt(m.group(1))); byte[] hash = Base64.getUrlDecoder().decode(m.group(2)); byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8); byte[] check = pbkdf2(password, salt, iterations); int zero = 0; for (int idx = 0; idx < check.length; ++idx) { zero |= hash[salt.length + idx] ^ check[idx]; } return zero == 0; } private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) { KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE); try { SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM); return f.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex); } catch (InvalidKeySpecException ex) { throw new IllegalStateException("Invalid SecretKeyFactory", ex); } } }
该实用程序类提供了对密码进行哈希处理 (hash) 和对用户进行身份验证 (authenticate) 的方法。它使用可定制的计算成本参数,并包含随机盐以提供额外的保护。通过利用此实用程序,您可以在 Java 应用程序中安全地存储和验证密码。
以上是如何使用 PBKDF2 在 Java 中安全地散列密码?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

将姓名转换为数字以实现排序的解决方案在许多应用场景中,用户可能需要在群组中进行排序,尤其是在一个用...

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

在使用IntelliJIDEAUltimate版本启动Spring...

在使用MyBatis-Plus或其他ORM框架进行数据库操作时,经常需要根据实体类的属性名构造查询条件。如果每次都手动...

Java对象与数组的转换:深入探讨强制类型转换的风险与正确方法很多Java初学者会遇到将一个对象转换成数组的�...

Redis缓存方案如何实现产品排行榜列表的需求?在开发过程中,我们常常需要处理排行榜的需求,例如展示一个�...

电商平台SKU和SPU表设计详解本文将探讨电商平台中SKU和SPU的数据库设计问题,特别是如何处理用户自定义销售属...
