Exporting a Certificate to a File : KeyStore « Security « Java






Exporting a Certificate to a File

     

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
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";
    Certificate cert = keystore.getCertificate(alias);

    File file = null;
    byte[] buf = cert.getEncoded();

    FileOutputStream os = new FileOutputStream(file);
    os.write(buf);
    os.close();

    Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
    wr.write(new sun.misc.BASE64Encoder().encode(buf));
    wr.flush();

  }
}

   
    
    
    
    
  








Related examples in the same category

1.Listing the Aliases in a Key Store: A key store is a collection of keys and certificates.
2.Listing the Aliases in a Key Store using keytool:
3.Retrieving a Key Pair from a Key Store
4.Create a keystore with a self-signed certificate, using the keytool command
5.Import a key/certificate pair from a pkcs12 file into a regular JKS format keystore
6.This program signs a certificate, using the private key of another certificate in a keystore.
7.This class imports a key and a certificate into a keystore