Executive summary: how do I install a new root certificate into Java using Java code?
We have a desktop application which accesses various web services. Recently one
If you want to install the certificate to the trusted root's keystore on the desktop machine, you will need permission to do that. It's the same with the keytool, you need a password to access the trusted root's keystore. If you want to be quick-n-dirty, you can
KeyTool
class (sun.security.tools.KeyTool
)But IMHO if the certificate is not valid, then it is not trustworthy. I would say there's a good reason for that.
Command-line solution. On the Mac, the Java home is /Library/Java/Home. Try:
$ sudo -i
# cd /Library/Java/Home
# keytool -import -trustcacerts -alias CAName -file CA.crt -keystore lib/security/cacerts
Substitute CAName with the name of your CA, and CA.crt with a path to your certificate file (PEM works). It will prompt for a keystore password. The default password is given in the linked article.
I had to do this for one of RapidSSL's CA certs.
I don't know if that is possible, but you could implement your own TrustManager to allow this connection or this CA. Here are the basics.
Sun published this code to create an updated version of your cacerts file based on any target host running https with any certs:
https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java
Your new cacerts will be named jssecacerts in the current directory. Just copy that new file over your jre/lib/security/cacerts file.
I make no comment about the security of your new cacerts file.
IMHO, Sun has not exposed keytool via an API, primarily to prevent developers from modifying the set of trusted CAs. I can very imagine attackers exploiting such code to insert their own root certificates into the trust store compromising the very model of the trust store.
In fact, if you look at the source of the KeyTool class (sun.security.tools package), not only is it final, it also has a private constructor preventing any caller from creating an instance of the KeyTool class from code. KeyTool does have a main method, making the commandline (and hence an OS user) possibly the only manner in which one can initialize and communicate with KeyTool.
The only (simplistic) approaches left would be:
You could always invoke KeyTool as a process Runtime.exec(...)
.