Skip to content

Instantly share code, notes, and snippets.

@InfoSec812
Created August 21, 2016 03:10
Show Gist options
  • Select an option

  • Save InfoSec812/4230b5fdde3d8b44485050e5b330d8ee to your computer and use it in GitHub Desktop.

Select an option

Save InfoSec812/4230b5fdde3d8b44485050e5b330d8ee to your computer and use it in GitHub Desktop.
An OpenLDAP compatible implementation of Secure SHA password hashing
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
class LDAPUtil {
/**
* Hash the provided password using SHA-1 and return base64 encoded password hash
*
* @param password The un-hashed password
* @return The hashed password
*/
static String hashPassword(byte[] salt, String password) {
String hashedPassword;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA1");
crypt.reset();
crypt.update(password.trim().getBytes());
crypt.update(salt);
byte[] hash = crypt.digest();
byte[] c = new byte[salt.length + hash.length];
System.arraycopy(hash, 0, c, 0, hash.length);
System.arraycopy(salt, 0, c, hash.length, salt.length);
hashedPassword = Base64.getEncoder().encodeToString(c);
} catch (NoSuchAlgorithmException nsae) {
LOG.error("Unable to get instance of SHA1 hashing object", nsae);
return null;
}
return hashedPassword;
// Remember to prepend '{SSHA}' to the base64 encoded string before storing to LDAP userPassword attribute!!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment