Code, JavaEE

Add Certificate to KeyStore


package principles;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
* KeystoreTest
*
* @author David King
*/
public class KeystoreTest {
private Logger LOG = LoggerFactory.getLogger(KeystoreTest.class);

@Test
public void testInstallCertificateFromStreamIntoKeyStore() {
// method extract (alias, certToImportInBytes, keystoreToAddCertTo, keystorePasswd)
KeyStore keyStore = null;
String davidkingKeyStore = "principles/davidking";
String davidkingKeyStoreStr = "davidking";
String certificateStr = "principles/principle.cer";
String alias = "someserver.net";
char[] passwd = "changeit".toCharArray();

BufferedInputStream certInputStream = null;
InputStream keystoreInputStream = null;

try {

keystoreInputStream = new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(davidkingKeyStore));

keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(keystoreInputStream, passwd);
keystoreInputStream.close();

certInputStream = new BufferedInputStream(new DataInputStream(getClass().getClassLoader().getResourceAsStream(certificateStr)));

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

while( certInputStream.available() > 0 ) {
Certificate certificate = certificateFactory.generateCertificate(certInputStream);

if (!keyStore.containsAlias(alias)) {
keyStore.setCertificateEntry(alias, certificate);
} else {
LOG.info("{} - alias already exists in keystore...", alias);
keyStore.deleteEntry(alias);
LOG.info("{} - alias deleted", alias);
keyStore.setCertificateEntry(alias, certificate);
LOG.info("Added alias - {}", alias);
}

}

keyStore.store(new FileOutputStream(new File(String.format("C:\\Temp\\principles\\src\\test\\resources\\principles\\%s", davidkingKeyStoreStr))), passwd);
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
LOG.error(e.getMessage(), e);
} finally {
if (certInputStream != null) {
try {
certInputStream.close();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
}

}

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s