Home / Java Patterns and Pitfalls     frequal.com

Fixing Bouncy Castle Startup Issues

If you are using the Bouncy Castle provider in your web app, and reloading the app causes errors like this:
SEVERE [https-jsse-nio-443-exec-27] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ABC] in context with path [/abc] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: java/security/spec/ECPublicKeySpec] with root cause
       java.lang.NoClassDefFoundError: java/security/spec/ECPublicKeySpec
               at org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi.engineGeneratePublic(Unknown Source)
               at java.security.KeyFactory.generatePublic(KeyFactory.java:328)
then you need to unload Bouncy Castle at app startup. To do so, add code like this in a class loaded at web app startup (this one is a ServletContextListener):
@WebListener
public class MyServletContextListener implements ServletContextListener {
  BouncyCastleProvider bcProvider = null;

  public MyServletContextListener() {
    if (bcProvider == null) {
      bcProvider = new BouncyCastleProvider();
      Provider[] providers = Security.getProviders();

      String name = bcProvider.getName();
      Security.removeProvider(name); // remove old instance

      Security.addProvider(bcProvider);
    }
  }

Kudos

Thanks to this post which showed me this technique.
Last modified on 5 Oct 2024 by AO

Copyright © 2024 Andrew Oliver