我如何在Java中哈哈密码?
-
30-09-2019 - |
题
我需要在数据库中存储哈希密码。我该如何在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);
}
}
其他提示
这里有一个 完整实施 用两种方法完全做您想要的事情:
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个随机字节,目的是,如果两个不同的人选择相同的密码,则存储的密码仍然看起来不同。
这 iterated_hash
, ,基本上是 hash(hash(hash(... hash(password, salt) ...)))
对于可以访问您的数据库来猜测密码,哈希并查找数据库中的哈希斯的潜在攻击者来说,它非常昂贵。你必须计算这个 iterated_hash
每次用户登录时,但是与攻击者相比,您花费了近100%的时间计算哈希。
bcrypt是一个非常好的图书馆,有一个 Java港口 它。
您可以使用 MessageDigest
, ,但这在安全方面是错误的。哈希不适用于存储密码,因为它们很容易损坏。
您应该使用另一种算法,例如bcrypt,pbkdf2和scrypt来存储密码。 看这里.
除了其他答案中提到的bcrypt和pbkdf2外,我还建议查看 Scrypt
不建议使用MD5和SHA-1,因为它们相对较快,因此使用“每小时租金”分布式计算(例如EC2)或现代的高端GPU可以使用蛮力 /词典攻击以相对较低的成本和合理的价格“破解”密码时间。
如果您必须使用它们,则至少要迭代该算法的预定量大量次数(1000+)。
请参阅此处的更多信息: https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords
和这里: http://codahale.com/how-to-safely-store-a-password/ (批评Sha Family,MD5等以进行密码哈希目的)
- 和这里: http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html (批评bcrypt并推荐Scrypt和PBKDF2)
完全同意埃里克森 PBKDF2 是答案。
如果您没有该选项,或者只需要使用哈希,那么Apache Commons Digestutils比正确处理JCE代码要容易得多:https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/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绑定 对于可以使用的原始(本地C)库。
在平均用例中,如果您选择PBKDF2而不是Argon2或vice-cice-a,我认为从安全的角度来看,这并不重要。如果您有强大的安全要求,我建议您在评估中考虑Argon2。
有关密码安全功能安全性的更多信息,请参见 Security.se.
在这里,您有两个有关MD5哈希和其他哈希方法的链接:
Javadoc API: http://java.sun.com/j2se/1.4.2/docs/api/java/java/security/messagedigest.html
您可以使用 春季安全性 加密 (只有 2个可选的编译依赖项),支持 PBKDF2, bcrypt 和 Scrypt 密码加密。
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
我只需遵循那里指定的算法,并使用Messagedigest进行哈希。
您需要按照建议将盐存储在数据库中。
我从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);
}
}