Skip to content

Instantly share code, notes, and snippets.

@ahmed-BH
Created July 23, 2019 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmed-BH/9e2ed74799c5e580e1848001cc4b8935 to your computer and use it in GitHub Desktop.
Save ahmed-BH/9e2ed74799c5e580e1848001cc4b8935 to your computer and use it in GitHub Desktop.
get sha256 representation of a string in java
public static String getSHA(String input)
{
// ------ Geeks For Geeks code ---------
try {
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
// digest() method called
// to calculate message digest of an input
// and return array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown" + " for incorrect algorithm: " + e);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment