0
votes

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?

1
Not that it matters but your code example doesn't use any features that are unique to Bouncycastle. You could just as easily done this without Bouncycastle. And explicitly specifying the provider in .getInstance() methods is usually a bad idea because it reduces portability. Does it really matter whose implementation of SHA-256 you use? It shouldn't. - President James K. Polk
Features unique to Bouncycastle were coming later once I could get the code to compile with a trivial example. - James Young
Sounds good, thank for your contribution. - President James K. Polk

1 Answers

0
votes

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