[java] 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?

This question is related to java bouncycastle sha256 jce

The answer is


When using hashcodes with any jce provider you first try to get an instance of the algorithm, then update it with the data you want to be hashed and when you are finished you call digest to get the hash value.

MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(in.getBytes());
byte[] digest = sha.digest();

you can use the digest to get a base64 or hex encoded version according to your needs


This is already implemented in the runtime libs.

public static String calc(InputStream is) {
    String output;
    int read;
    byte[] buffer = new byte[8192];

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] hash = digest.digest();
        BigInteger bigInt = new BigInteger(1, hash);
        output = bigInt.toString(16);
        while ( output.length() < 32 ) {
            output = "0"+output;
        }
    } 
    catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }

    return output;
}

In a JEE6+ environment one could also use JAXB DataTypeConverter:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

Using Java 8

MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);        
System.out.println(encoded.toLowerCase());

I suppose you are using a relatively old Java Version without SHA-256. So you must add the BouncyCastle Provider to the already provided 'Security Providers' in your java version.

    // NEEDED if you are using a Java version without SHA-256    
    Security.addProvider(new BouncyCastleProvider());

    // then go as usual 
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "my string...";
    md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
    byte[] digest = md.digest();

You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?

Keep up the good work !


return new String(Hex.encode(digest));

Java 8: Base64 available:

    MessageDigest md = MessageDigest.getInstance( "SHA-512" );
    md.update( inbytes );
    byte[] aMessageDigest = md.digest();

    String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
    return( outEncoded );

This will work with "org.bouncycastle.util.encoders.Hex" following package

return new String(Hex.encode(digest));

Its in bouncycastle jar.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to bouncycastle

How to export non-exportable private key from store Hash String via SHA-256 in Java scp via java

Examples related to sha256

PHP salt and hash SHA256 for login password Are there any SHA-256 javascript implementations that are generally considered trustworthy? Mismatch Detected for 'RuntimeLibrary' SHA-256 or MD5 for file integrity Hashing a string with Sha256 How to hash some string with sha256 in Java? Generating a SHA-256 hash from the Linux command line Hash String via SHA-256 in Java Generate sha256 with OpenSSL and C++ How long is the SHA256 hash?

Examples related to jce

How to create a secure random AES key in Java? Trust Store vs Key Store - creating with keytool Why java.security.NoSuchProviderException No such provider: BC? Hash String via SHA-256 in Java How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?