简体   繁体   中英

Unit Testing SSL at REST APIs

I have a restlet application which runs via SSL. I've created a keystore for it and extracted the certificate from it.

I want to test my SSL restlet application however I need to import that certificate into my truststore as well. I tried that and it seems to work at my machine:

final char sep = File.separatorChar;
File dir = new File(System.getProperty("java.home") + sep + "lib" + sep + "security");
File file = new File(dir, "cacerts");
InputStream localCertIn = new FileInputStream(file);

KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(localCertIn, null);

if (keystore.containsAlias("mycertalias")) {
  localCertIn.close();
  return;
}

localCertIn.close();

InputStream certIn = new FileInputStream("src/test/mycert.cer");
BufferedInputStream bis = new BufferedInputStream(certIn);
CertificateFactory cf = CertificateFactory.getInstance("X.509");

while (bis.available() > 0) {
  Certificate cert = cf.generateCertificate(bis);
  keystore.setCertificateEntry("mycertalias", cert);
}

certIn.close();

OutputStream out = new FileOutputStream(file);
keystore.store(out, null);
out.close();

However, it works with null as password and with changeit or password (password of my keytstore).

This piece of code does not work some other computers (not a generic solution). If you put your java home into a file path which needs permission it throws error.

So, is there any way to create another truststore and work with that to test my SSL?

As per code it should be working fine in your system or any other system. As per my ssl knowledge that certificate you have extracted has a dependency with your system. So you have to extract or prepare new certificate that should be trusted by not only your machine it should be trusted by all the machine.

It's working with no password becouse you use null as password in the keystore.store() method call, use instead .

keystore.store(out, "password".toCharArray() );

Yours,

I've found a solution with this way: I've declared my keystore as trust keystore during my test. So, it's been a generic solution for other computers. I've also set a password for my test trust keystore that will be used during my test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM