Adding a Certificate to a Key Store : Certificate « Security « Java






Adding a Certificate to a Key Store

   
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;

public class Main {
  public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";
    char[] password = "password".toCharArray();

    Certificate cert = keystore.getCertificate(alias);

    File keystoreFile = new File("your.keystore");
    // Load the keystore contents
    FileInputStream in = new FileInputStream(keystoreFile);
    keystore.load(in, password);
    in.close();

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

    // Save the new keystore contents
    FileOutputStream out = new FileOutputStream(keystoreFile);
    keystore.store(out, password);
    out.close();

  }
}

   
    
    
  








Related examples in the same category

1.Signature Test
2.Specify the keystore of certificates using the javax.net.ssl.keyStore system property:
3.Retrieving a Certificate from a Key Store
4.Creating a Certification Path
5.Listing the Most-Trusted Certificate Authorities (CA) in a Key Store
6.Validating a Certification Path using the most-trusted CAs in the JDK's cacerts file.
7.Importing a Certificate from a File
8.Retrieving the Certification Path of an SSL Server
9.Getting the Subject and Issuer Distinguished Names of an X509 Certificate
10.Creates a CertStore from the contents of a file-system directory.