Search code examples
javaandroidbouncycastle

Bouncy castle no such provider exception


I have added the bouncy castle jar file to my application class path in android and in java. This is the code that I've used in both of them. But it doesn't seem to recognize the provider "BC".

SecureRandom sr1=new SecureRandom().getInstance("SHA1PRNG", "BC");
      System.out.println(sr1.getProvider());
      sr1.setSeed(12);
      byte[] a=new byte[0];
      sr1.nextBytes(a);
      int ai=a[0];
      System.out.println(ai);


It throws the following exception in both android and in java:

java.security.NoSuchProviderException: no such provider: BC


How to correct this?
I had not added the provider in the policy file. After doing that I am getting the following exception.

java.security.NoSuchAlgorithmException: no such algorithm: SHA1PRNG for provider
 BC<br>

Does it mean that bouncy castle does not provide an implementation of "SHA1PRNG" algorithm? But the whole reason I imported bouncy castle was to have a common provider in both android and in java, so that the sequence of random numbers generated with the same seed are the same in both android and java.


Solution

  • Apparently it doesn't provide a SecureRandom implementation at all. You can get the system implementation (from Harmony) like this (no need to create an instance to call static method):

    SecureRandom.getInstance("SHA1PRNG")
    

    BouncyCastle has DigestRandomGenerator which could probably used in a similar manner, but may or may not be compatible with the Sun SHA1PRNG (which appears to be proprietary, and really well defined)

    Re: generating OTPs using SecureRandom: SecureRandom with a fixed seed is not the right tool for this. To generate OTPs, you should use a secret key combined with a predictable element (time or a counter). A standard way is using an HMAC as specified by e.g. OATH. Read RFC 4226 for details.