KPthunder KPthunder - 2 months ago 20
Java Question

Hash String via SHA-256 in Java

By looking around here as well as the internet in general, I have found Bouncy Castle. I want to use Bouncy Castle (or some other freely available utility) to generate a SHA-256 Hash of a String in Java. Looking at their documentation I can't seem to find any good examples of what I want to do. Can anybody here help me out?


If all you want to do is hash a string, I'd just use the built-in MessageDigest class.

MessageDigest md = MessageDigest.getInstance("SHA-256");
String text = "This is some text";

md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed
byte[] digest = md.digest();

Tada, digest now contains the hash of your string.

If you want to format to hex with left zero padding:

String.format("%064x", new java.math.BigInteger(1, digest));