Tag Archives: password

Hashing password in Java and Groovy

hash
If you have to get a hash from string, you can use next:

In java:

public static String getPasswordHash(String value) {
  byte[] bytesOfPassword = value.getBytes("UTF-8");
  MessageDigest md = MessageDigest.getInstance("SHA-256");
  md.update(bytesOfPassword);
  byte[] bytesOfEncryptedPassword = md.digest();
  return new String(bytesOfEncryptedPassword);
}

In Groovy (with Base64 encoding!):

def sha256Hash = { text ->
  java.security.MessageDigest.getInstance("SHA-256") 
    .digest(text.getBytes("UTF-8")).encodeBase64().toString()
}