Creating sha256 password hashes
Java
The following code snippet is an example on how to generate SHA 256 hash of a String in Java
public String generateHash(String value) {
String password=null;
try {
byte[] valueBytes = value.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] encodedBytes = md.digest(valueBytes);
String hexEncodedValue = toHexString(encodedBytes);
password = hexEncodedValue;
} catch (UnsupportedEncodingException e) {
//should not happen, just log.
log.error(e.getMessage(), e);
} catch (NoSuchAlgorithmException e) {
//should not happen, just log.
log.error(e.getMessage(), e);
}
return password;
}
/**
* Fast convert a byte array to a hex string
* with possible leading zero.
* @param b array of bytes to convert to string
* @return hex representation, two chars per byte.
*/
public static String toHexString (byte[] b) {
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i=0; i < b.length; i++) {
// look up high nibble char
sb.append(hexChar[( b[i] & 0xf0) >>> 4]);
// look up low nibble char
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}
/**
* table to convert a nibble to a hex char.
*/
static char[] hexChar = {
'0' , '1' , '2' , '3' ,
'4' , '5' , '6' , '7' ,
'8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f'};