Skip to content

Instantly share code, notes, and snippets.

@ansig
Created November 8, 2014 07:44
Show Gist options
  • Save ansig/a90b5f680a748eefb538 to your computer and use it in GitHub Desktop.
Save ansig/a90b5f680a748eefb538 to your computer and use it in GitHub Desktop.
Hash a password using PBKDF2 with hman and sha1 algorithm.
import com.sun.org.apache.xml.internal.security.utils.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
/**
* Hash a password using PBKDF2 with hman and sha1 algorithm.
*/
public class PBKDF2PasswordHasher {
public static final String ALGORITHM = "PBKDF2WithHmacSHA1";
public static final int SALT_BYTES = 16;
public static final int KEY_BITS = 128;
public static final int ITERATIONS = 65536;
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
String password = "Password";
System.out.printf("This is the password: %s%n", password);
// Generate random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_BYTES];
random.nextBytes(salt);
System.out.printf("This is the salt: %s%n", Base64.encode(salt));
// Hash the password
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, ITERATIONS, KEY_BITS);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
byte[] hash = factory.generateSecret(spec).getEncoded();
// Using Base64 to properly encode hash bytes into a string of characters
System.out.printf("This is the hash: %s%n", Base64.encode(hash));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment