Exporting a Certificate to a File - Java Security

Java examples for Security:Certificate

Description

Exporting a Certificate to a File

Demo Code


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

public class Main {
  public static void export(java.security.cert.Certificate cert, File file,
      boolean binary) {
    try {//from  w w  w.j a  va  2  s.com
      // Get the encoded form which is suitable for exporting
      byte[] buf = cert.getEncoded();

      FileOutputStream os = new FileOutputStream(file);
      if (binary) {
        // Write in binary form
        os.write(buf);
      } else {
        // Write in text form
        Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
        wr.write("-----BEGIN CERTIFICATE-----\n");
        wr.write(new sun.misc.BASE64Encoder().encode(buf));
        wr.write("\n-----END CERTIFICATE-----\n");
        wr.flush();
      }
      os.close();
    } catch (Exception e) {
    }
  }
}

// Export in binary
> keytool -storepass my-keystore-password -alias myalias -export -file outfilename.cer

// Export in text format
> keytool -storepass my-keystore-password -alias myalias -export -rfc -file outfilename.cer
-----BEGIN CERTIFICATE-----
your CERTIFICATE
-----END CERTIFICATE-----

Related Tutorials