4

I am implementing a server that uses self-signed certificates. What is the best way to distribute the certificates to the clients? I could import the certificate into the java keystore and setup the client. But is there any way to avoid every client from importing the certificate manually. Can this be done automatically by the java client? I went through the JSSE reference but could not figure out how to do this. Would appreciate any help.

Regards, Sampath.

Sampath Herga
  • 101
  • 2
  • 4
  • See this SO answer: http://stackoverflow.com/questions/2893819/telling-java-to-accept-self-signed-ssl-certificate Regards – Sorin Feb 28 '12 at 11:09
  • 1
    @Sorin, avoid the trustmanager in the accepted answer to that question. Instead, the method in this answer should be used: http://stackoverflow.com/a/859271/372643 – Bruno Feb 28 '12 at 13:23
  • I did have a look at that before posting. In that it mentioned using the keytool to import the certificate. Does that mean that the user needs to download the certificate manually on the machine. I was looking for a way where this exchange could be done automatically. – Sampath Herga Feb 28 '12 at 13:58

1 Answers1

0

Check out the KeyStore class. It allows you to manipulate Java keystores.

Code example:

KeyStore ks = KeyStore.getInstance("JKS");  
ks.load(null, null);  // Creates a new keystore

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("cert.cer"));  // Or read from URL
CertificateFactory cf = CertificateFactory.getInstance("X.509");  
Certificate cert = null;  

if (bis.available() > 0) {  
  cert = cf.generateCertificate( bis );  
  ks.setCertificateEntry( "SGCert", cert );  
}  

ks.setCertificateEntry("SGCert", cert);  
ks.store(new FileOutputStream("out.keystore"), "secret".toCharArray() ); 
nfechner
  • 17,295
  • 7
  • 45
  • 64
  • Thanks for the example. Where does the cert.cer come from. Does it have to be downloaded from the server? – Sampath Herga Feb 28 '12 at 13:59
  • Bad formatting on my part: You can scroll to the right to see a code comment that says: `// Or read from URL` You can use a URL instead of the filename to read the cert from. The other way would be to include the cert with your client installer. – nfechner Feb 28 '12 at 14:13
  • My bad. Should have read fully. Let me try that approach. Thanks again. – Sampath Herga Feb 28 '12 at 15:11
  • Sorry to dig up an old question. But what is the "correct" way to do this? Wouldn't getting the certificate from the URL be unsafe? – Dave Aug 14 '12 at 18:01
  • @Dave That depends a lot on where the URL comes from. If it's from external input, there is a possibility of a risk (depending on the strength of Javas implementation). – nfechner Aug 15 '12 at 09:45