Search code examples
javacryptographybouncycastle

How to use BouncyCastle with Java?


I have read the notes on Bouncy Castle's website, and read how to add the security provider in Java Cryptography, Tools and Techniques, but I am still stuck at basic usage.

I have the JAR: bcprov-jdk15on-167.jar (in my "current directory" with source)

and some code:

// import what for Bouncy Castle?

public class DigestDemo
{
   public static String byteArrayToHex(byte[] a)
   {
      StringBuilder sb = new StringBuilder(a.length * 2);
      for(byte b: a)
        sb.append(String.format("%02x", b));
      return sb.toString();
   }

   public static byte[] computeDigest(String digestName, byte[] data) throws NoSuchProviderException, 
    NoSuchAlgorithmException
   {
       MessageDigest digest = MessageDigest.getInstance(digestName, "BC");
       digest.update(data);
       return digest.digest();
   }

   public static void main(String[] args) throws Exception
   {
       Security.addProvider(new BouncyCastleProvider());
       System.out.println(byteArrayToHex(computeDigest("SHA-256", "Hello World!".getBytes())));
   }
}

but I am stuck at how to run simple examples.

The instructions say that the JAR must be on the classpath (with the latest Java versions jre/lib/ext is not a supported location anymore). So I have it in my current directory ready to run with the -cp command line option. Whatever I provide for imports doesn't seem to work, since javac can't find the packages.

Question is how to compile so I can use Bouncy Castle?


Solution

  • The import line is:

    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    

    I can then specify the classpath using javac the same way as java.

    So, using Powershell:

    javac -cp .\bcprov-ext-jdk15on-167.jar .\DigestDemo.java
    

    and to run:

    java -cp ";.\bcprov-ext-jdk15on-167.jar;." DigestDemo