你在說什麼是醃製散列。
這就是我的做法。
public static byte[] getSecure8ByteSalt(){
SecureRandom random = null;
try {
random = SecureRandom.getInstance("SHA1PRNG");
byte [] bSalt = new byte[8];
random.nextBytes(bSalt);
return bSalt;
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(),e);
}
return new byte[]{
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
};
}
,對於鹽調用的方法被稱爲散列:
private void hash(String passwd, int hashType){
byte[] bSalt = new byte[8];
try {
if(this.salt == null){
bSalt = getSecure8ByteSalt();
}
else{
bSalt = base64ToByte(salt);
}
} catch (IOException e1) {
log.error(e1.getMessage(),e1);
return;
}
byte[] bDigest=null;
try {
bDigest = getHash(ITERATION_NUMBER,passwd,bSalt,hashType);
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(),e);
}
String sDigest = byteToBase64(bDigest);
if(this.salt == null)
setSalt(byteToBase64(bSalt));
setPasswordHash(sDigest);
}
字節到基座64方法:
public static byte[] base64ToByte(String data) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(data);
}
public static String byteToBase64(byte[] data){
BASE64Encoder endecoder = new BASE64Encoder();
return endecoder.encode(data);
}
的getHash方法:
private byte[] getHash(int iterationNb, String password, byte[] salt, int hashType) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(HASH_TYPE[hashType]);
digest.reset();
digest.update(salt);
byte[] input = null;
try {
input = digest.digest(password.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(),e);
}
for (int i = 0; i < iterationNb; i++) {
digest.reset();
input = digest.digest(input);
}
return input;
}
來源
2011-08-14 10:43:02
Ali
我不鼓勵你使用'MD5'。我會建議當然最低'SHA256'鹽。在我的代碼中,你可以傳遞'MD5'或'SHA-512'或'SHA-256',但是'MD5'(128位)幾乎沒有'SHA-1'(160-bit)那麼安全。 'SHA-256'(256位)。你可以使用更安全的'TripleDES'。 – Ali
@Ali是的,我知道SHA和MD5的差異以及如何使用它們。我想要實現MD5的算法。不過謝謝。 – Matt
這裏要實現的關鍵是(除了append意味着最終的事實):MD5和其他散列函數是在位而不是字節上定義的。從理論上講,你可以散列一個13位長的消息,其結果將不同於散列一個以開始或結束方式相同的16位長消息。但實際上,幾乎所有的實現(包括您的所有可能性)都假定輸入消息由整個字節組成。 –