Adding a Certificate to a Key Store - Java Security

Java examples for Security:Certificate

Description

Adding a Certificate to a Key Store

Demo Code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

public class Main {
  public static void addToKeyStore(File keystoreFile, char[] keystorePassword,
      String alias, java.security.cert.Certificate cert) {
    try {/*from w  w w  .  j  a va  2s  .  c  om*/
      // Create an empty keystore object
      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

      // Load the keystore contents
      FileInputStream in = new FileInputStream(keystoreFile);
      keystore.load(in, keystorePassword);
      in.close();

      // Add the certificate
      keystore.setCertificateEntry(alias, cert);

      // Save the new keystore contents
      FileOutputStream out = new FileOutputStream(keystoreFile);
      keystore.store(out, keystorePassword);
      out.close();
    } catch (java.security.cert.CertificateException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (FileNotFoundException e) {
    } catch (KeyStoreException e) {
    } catch (IOException e) {
    }
  }
}

Related Tutorials