Search code examples
javahashbouncycastle

How to use BouncyCastle for calculating Message Digests?


I'm currently playing around with Java and hashing.

I came across bouncycastle when I was looking around online, I got it installed in my IDE and everything.

But, how do I use it to hash a text using the algorithms found here? (Look for section 5.2 Algorithms)

I only want to use the digest algorithms as defined in this section:

GOST3411 - MD2 - MD4 - MD5 - RipeMD128 - RipeMD160 - RipeMD256 - RipeMD320 - SHA1 - SHA-224 - SHA-256 - SHA-384 - SHA-512 - SHA3-224 - SHA3-256 - SHA3-384 - SHA3-512 - Skein-256-* - Skein-512-* - Skein-1024-* - Tiger - Whirlpool


Solution

  • I've completely edited my answer, given the clarification of the original question. To hash a string with an SHA-512 digest algorithm, you need to register BouncyCastle with the JVM, then, you can use the Java APIs or BouncyCastle classes directly.

    E.g. Java APIs

    // register the BouncyCastleProvider with the Security Manager
    Security.addProvider(new BouncyCastleProvider());
    
    String plainString = "Plaintext Secret";
    
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
    byte[] hashedString = messageDigest.digest(plainString.getBytes());
    
    doSomething().with(hashedString);
    

    Alternately you can use the BouncyCastle API directly, but it is better (IMO) to use the Java APIs for portability, if you can. (What if you find a library that is better than BouncyCastle? Doubtful, but you see the point.)

    Security.addProvider(new BouncyCastleProvider());
    
    String plainString = "Plaintext Secret";
    
    // instantiate the BouncyCastle digest directly.
    MessageDigest messageDigest = new SHA512Digest();
    byte[] hashedString = messageDigest.digest(plainString.getBytes());
    
    doSomething().with(hashedString);