Reputation: 3118
I am working on a Java web application that is being deployed on a Tomcat server. I have make use of several cryptographic functions at several points in the application. I want to use Bouncycastle as my security provider.
I am not sure where I have to call Security.addProvider(new BouncyCastleProvider());
. Does this have to happen on a per-method basis or should this only be done on start. Where the provider be added?
Upvotes: 1
Views: 1447
Reputation: 3155
In general, I prefer to configure the security provider in a lazy manner so that my code does not depend on the provider being previously initialized. If you are using dependency injection you can define a class like the following:
public class SecurityProvider {
public SecurityProvider() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
And inject it into any object which requires the SecurityProvider to be initialized. The dependency injection container will instantiated the SecurityProvider as necessary.
If you are using plain servlets you can register a ServletContextListener that initializes the SecurityProvider.
public class SecurityProviderInitializer implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Upvotes: 3