Skip to content

Instantly share code, notes, and snippets.

@zbigniewTomczak
Created March 7, 2013 14:32
Show Gist options
  • Save zbigniewTomczak/5108430 to your computer and use it in GitHub Desktop.
Save zbigniewTomczak/5108430 to your computer and use it in GitHub Desktop.
Salt plus iterative hash password generation in Java. Salt should be stored next to hashed password for authentication. This algorithm can be enhanced with second salt - application wide salt. Another variation is concatenating it with username. Hashing calculation algorithm should be kept safe.
import java.nio.*;
import java.nio.charset.*;
import java.security.*;
import java.util.*;
public class StorePassword {
public static int hashCount = 10000;
public static String hashAlgorithm = "SHA-512";
public static String charset = "UTF-8";
public static void main(String[] args) throws NoSuchAlgorithmException{
char[] password = System.console().readPassword("Please enter your password:");
CharBuffer charBuffer = CharBuffer.wrap(password);
ByteBuffer bf = Charset.forName(charset).encode(charBuffer);
byte[] salt = new byte[64];
new Random().nextBytes(salt);
byte[] hashed = getHash(bf.array());
System.out.println(hashed.length);
System.out.println(Arrays.toString(hashed));
}
public static byte[] getHash(byte[] password, byte[] salt) throws NoSuchAlgorithmException{
MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
digest.reset();
digest.update(salt);
byte[] hash = digest.digest(password);
for (int i = 0; i < hashCount; i++) {
digest.reset();
hash = digest.digest(hash);
}
return hash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment