首頁 >Java >java教程 >如何使用 PBKDF2 在 Java 中安全地散列密碼?

如何使用 PBKDF2 在 Java 中安全地散列密碼?

Patricia Arquette
Patricia Arquette原創
2024-12-29 12:38:14771瀏覽

How to Securely Hash Passwords in Java Using PBKDF2?

如何在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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn