質問

データベースに保存するためにパスワードをハッシュする必要があります。 Javaでこれを行うにはどうすればよいですか?

プレーンテキストのパスワードを取得し、ランダム塩を追加してから、データベースに塩とハッシュパスワードを保管したいと考えていました。

次に、ユーザーがログインしたいときに、提出されたパスワードを取得し、アカウント情報からランダムソルトを追加し、ハッシュして、アカウント情報で保存されたハッシュパスワードに相当するかどうかを確認できます。

役に立ちましたか?

解決

Javaランタイムに組み込まれた施設を実際に使用してこれを行うことができます。 Java 6のSunjceはPBKDF2をサポートしています。これは、パスワードハッシュに使用するのに適したアルゴリズムです。

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;

/**
 * Hash passwords for storage, and test passwords against password tokens.
 * 
 * Instances of this class can be used concurrently by multiple threads.
 *  
 * @author erickson
 * @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
 */
public final class PasswordAuthentication
{

  /**
   * Each token produced by this class uses this identifier as a prefix.
   */
  public static final String ID = "$31$";

  /**
   * The minimum recommended cost, used by default
   */
  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("\\$31\\$(\\d\\d?)\\$(.{43})");

  private final SecureRandom random;

  private final int cost;

  public PasswordAuthentication()
  {
    this(DEFAULT_COST);
  }

  /**
   * Create a password manager with a 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 a password in an immutable {@code String}. 
   * 
   * <p>Passwords should be stored in a {@code char[]} so that it can be filled 
   * with zeros after use instead of lingering on the heap and elsewhere.
   * 
   * @deprecated Use {@link #hash(char[])} instead
   */
  @Deprecated
  public String hash(String password)
  {
    return hash(password.toCharArray());
  }

  /**
   * Authenticate with a password in an immutable {@code String} and a stored 
   * password token. 
   * 
   * @deprecated Use {@link #authenticate(char[],String)} instead.
   * @see #hash(String)
   */
  @Deprecated
  public boolean authenticate(String password, String token)
  {
    return authenticate(password.toCharArray(), token);
  }

}

他のヒント

がここにあります 完全な実装 2つの方法であなたが望むことを正確に行うことで:

String getSaltedHash(String password)
boolean checkPassword(String password, String stored)

ポイントは、攻撃者がデータベースコードとソースコードの両方にアクセスできる場合でも、パスワードが安全であるということです。

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Base64;

public class Password {
    // The higher the number of iterations the more 
    // expensive computing the hash is for us and
    // also for an attacker.
    private static final int iterations = 20*1000;
    private static final int saltLen = 32;
    private static final int desiredKeyLen = 256;

    /** Computes a salted PBKDF2 hash of given plaintext password
        suitable for storing in a database. 
        Empty passwords are not supported. */
    public static String getSaltedHash(String password) throws Exception {
        byte[] salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLen);
        // store the salt with the password
        return Base64.encodeBase64String(salt) + "$" + hash(password, salt);
    }

    /** Checks whether given plaintext password corresponds 
        to a stored salted hash of the password. */
    public static boolean check(String password, String stored) throws Exception{
        String[] saltAndHash = stored.split("\\$");
        if (saltAndHash.length != 2) {
            throw new IllegalStateException(
                "The stored password must have the form 'salt$hash'");
        }
        String hashOfInput = hash(password, Base64.decodeBase64(saltAndHash[0]));
        return hashOfInput.equals(saltAndHash[1]);
    }

    // using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
    // cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
    private static String hash(String password, byte[] salt) throws Exception {
        if (password == null || password.length() == 0)
            throw new IllegalArgumentException("Empty passwords are not supported.");
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey key = f.generateSecret(new PBEKeySpec(
            password.toCharArray(), salt, iterations, desiredKeyLen));
        return Base64.encodeBase64String(key.getEncoded());
    }
}

保管しています 'salt$iterated_hash(password, salt)'. 。塩は32のランダムバイトであり、2人の異なる人が同じパスワードを選択した場合、保存されたパスワードは依然として異なるように見えることです。

iterated_hash, 、基本的にです hash(hash(hash(... hash(password, salt) ...))) データベースにアクセスできる潜在的な攻撃者がパスワードを推測し、ハッシュし、データベースのハッシュを検索する潜在的な攻撃者にとって非常に高価になります。これを計算する必要があります iterated_hash ユーザーがログインするたびにログインしますが、時間のほぼ100%をコンピューティングハッシュに費やす攻撃者と比較して、それほど費用はかかりません。

bcryptは非常に良いライブラリであり、 Javaポート それの。

使用してハッシュを計算できます MessageDigest, 、しかし、これはセキュリティの点で間違っています。ハッシュは、パスワードを簡単に壊すことができるため、保存に使用することはできません。

Bcrypt、PBKDF2、Scryptなどの別のアルゴリズムを使用して、パスワードを保存する必要があります。 こちらをご覧ください.

使用できます シロ 図書館(以前 jsecurity) 実装 説明されているものの owasp.

また、jasyptライブラリにはaがあります 同様のユーティリティ.

他の回答で言及されているbcryptとpbkdf2に加えて、私は見ることをお勧めします scrypt

MD5とSHA-1は、比較的速いため、「1時間あたりの家賃」分散コンピューティング(EC2など)を使用して、または最新のハイエンドGPUを使用して、比較的低コストと妥当なブルートフォース /辞書攻撃を使用してパスワードを「クラック」できます。時間。

それらを使用する必要がある場合は、少なくともアルゴリズムを事前定義されたかなりの回数(1000+)を反復します。

エリクソンに完全に同意します PBKDF2 答えです。

そのオプションがない場合、またはハッシュのみを使用する必要がある場合、Apache Commons DigestutilsはJCEコードを正しくするよりもはるかに簡単です。https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/digestutils.html

ハッシュを使用する場合は、SHA256またはSHA512を使用してください。このページには、パスワードの処理とハッシュに関する良い推奨事項があります(パスワード処理のためにハッシュすることをお勧めしないことに注意してください):http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html

一方 NIST推奨PBKDF2 すでに言及されています、私は大衆がいたことを指摘したいと思います パスワードハッシュ競争 それは2013年から2015年まで実行されました。最終的には、 Argon2 推奨されるパスワードハッシュ機能として選択されました。

かなりよく採用されています Java Binding 使用できるオリジナル(ネイティブC)ライブラリの場合。

平均的なユースケースでは、Argon2またはその逆よりもPBKDF2を選択した場合、セキュリティの観点からは重要ではないと思います。強力なセキュリティ要件がある場合は、評価でArgon2を検討することをお勧めします。

パスワードハッシュ機能のセキュリティに関する詳細については、参照してください security.se.

ここには、MD5ハッシュとその他のハッシュメソッドの2つのリンクがあります。

Javadoc API: http://java.sun.com/j2se/1.4.2/docs/api/java/security/messagegest.html

チュートリアル: http://www.twmacinta.com/myjava/fast_md5.php

使用できます スプリングセキュリティ 暗号 (持っているだけです 2オプションのコンパイル依存関係)、サポート PBKDF2, bcryptscrypt パスワード暗号化。

SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder();
String sCryptedPassword = sCryptPasswordEncoder.encode("password");
boolean passwordIsValid = sCryptPasswordEncoder.matches("password", sCryptedPassword);
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String bCryptedPassword = bCryptPasswordEncoder.encode("password");
boolean passwordIsValid = bCryptPasswordEncoder.matches("password", bCryptedPassword);
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder();
String pbkdf2CryptedPassword = pbkdf2PasswordEncoder.encode("password");
boolean passwordIsValid = pbkdf2PasswordEncoder.matches("password", pbkdf2CryptedPassword);

すべての標準的なハッシュスキームの中で、LDAP SSHAは最も安全なものです。

http://www.openldap.org/faq/data/cache/347.html

そこで指定されたアルゴリズムに従って、Messaged Gigestを使用してハッシュを行います。

提案したように、データベースに塩を保存する必要があります。

私はUdemyのビデオからそれを傾け、より強力なランダムパスワードになるように編集しました

}

private String pass() {
        String passswet="1234567890zxcvbbnmasdfghjklop[iuytrtewq@#$%^&*" ;

        char icon1;
        char[] t=new char[20];

         int rand1=(int)(Math.random()*6)+38;//to make a random within the range of special characters

            icon1=passswet.charAt(rand1);//will produce char with a special character

        int i=0;
        while( i <11) {

             int rand=(int)(Math.random()*passswet.length());
             //notice (int) as the original value of Math>random() is double

             t[i] =passswet.charAt(rand);

             i++;
                t[10]=icon1;
//to replace the specified item with icon1
         }
        return new String(t);
}






}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top