一般我们存储密码的时候,使用hash算法进行存储,但是,这样做是不安全的,虽然不能反向生成密码,但是可以通过彩虹法和反向查表法高效的猜解出密码。
比较安全的做法就是使用hash+salt的加密算法。
这里使用了RFC2898标准。
看代码:
Rfc2898DeriveBytes.java
package com.poreader.common;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* This implementation follows RFC 2898 recommendations. See
* http://www.ietf.org/rfc/Rfc2898.txt
*/
public class Rfc2898DeriveBytes {
private static final int BLOCK_SIZE = 20;
private static Random random = new Random();
private Mac hmacsha1;
private byte[] salt;
private int iterations;
private byte[] buffer = new byte[BLOCK_SIZE];
private int startIndex = 0;
private int endIndex = 0;
private int block = 1;
/**
* Creates new instance.
*
* @param password
* The password used to derive the key.
* @param salt
* The key salt used to derive the key.
* @param iterations
* The number of iterations for the operation.
* @throws NoSuchAlgorithmException
* HmacSHA1 algorithm cannot be found.
* @throws InvalidKeyException
* Salt must be 8 bytes or more. -or- Password cannot be null.
*/
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) throws NoSuchAlgorithmException,
InvalidKeyException {
this.salt = salt;
this.iterations = iterations;
this.hmacsha1 = Mac.getInstance("HmacSHA1");
this.hmacsha1.init(new SecretKeySpec(password, "HmacSHA1"));
}
/**
* Creates new instance.
*
* @param password
* The password used to derive the key.
* @param salt
* The key salt