'Java library with different versions of Bouncy Castle

I'm creating a Java library that is dependent on FIPS compliant Bouncy Castle but I also want the same library to be compatible with the regular Bouncy Castle

I know that I'll end up with two packages to be published to Maven, similar to how java-webauthn-server create their minimal jar that does not depend on Bouncy Castle.

So, my question is, what is the correct way to create a code that can instantiate one or the other version of the provider based on what the version of the library.

Here is my code that I use to instantiate a provider:


//import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider
import org.bouncycastle.jce.provider.BouncyCastleProvider

...
//    Provider provider = new BouncyCastleFipsProvider()
    Provider provider = new BouncyCastleProvider()
...


Solution 1:[1]

One option is to use reflection to instantiate the available provider:

Provider getProvider() throws ClassNotFoundException {
    try {
        return (Provider) Class.forName("org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider").getDeclaredConstructor().newInstance();
    } catch (ClassNotFoundException ex) {
        // fallback
        return (Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").getDeclaredConstructor().newInstance();

    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1