Skip to content
On this page

BouncyCastle

We know that the Java standard library provides a series of commonly used hash algorithms.

But what if the algorithm we need is not provided by the Java standard library?

Method 1: Write it yourself, which is highly challenging.

Method 2: Find an existing third-party library and use it directly.

BouncyCastle is a third-party library that offers many hash and encryption algorithms not available in the Java standard library. For example, it provides the RipeMD160 hash algorithm.

Let’s look at how to use algorithms provided by the BouncyCastle third-party library.

Using BouncyCastle for RipeMD160

First, we must add the BouncyCastle-provided JAR file to the classpath. This JAR file is named bcprov-jdk18on-xxx.jar and can be downloaded from the official website.

The Java standard library’s java.security package provides a standard mechanism that allows third-party providers to integrate seamlessly. To use BouncyCastle’s RipeMD160 algorithm, we need to register BouncyCastle first:

java
import java.security.MessageDigest;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws Exception {
        // Register BouncyCastle:
        Security.addProvider(new BouncyCastleProvider());
        // Invoke normally by name:
        MessageDigest md = MessageDigest.getInstance("RipeMD160");
        md.update("HelloWorld".getBytes("UTF-8"));
        byte[] result = md.digest();
        System.out.println(HexFormat.of().formatHex(result));
    }
}

In the above code, registering BouncyCastle is done using the following statement:

java
Security.addProvider(new BouncyCastleProvider());

Registration only needs to be performed once at startup, after which you can use all the hash and encryption algorithms provided by BouncyCastle.

Exercise

Use BouncyCastle’s RipeMD160 to compute a hash.

Summary

  • BouncyCastle is an open-source third-party algorithm provider.
  • BouncyCastle offers many hash and encryption algorithms that are not available in the Java standard library.
  • Before using third-party algorithms, you need to register them using Security.addProvider().
BouncyCastle has loaded