Java Security Certificate convert

Description

Java Security Certificate convert

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class Main {
   public static void main(String args[]) {
      try {/*from  w  w w  .j  av  a 2  s  .  c om*/
         InputStream inStream = new FileInputStream(args[1]);
         CertificateFactory cf = CertificateFactory.getInstance("X.509");
         Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
         byte[] buf = cert.getEncoded();

         if (args[0].equals("fromder")) {
            Writer wr = new OutputStreamWriter(new FileOutputStream(args[2]));
            wr.write("-----BEGIN CERTIFICATE-----".toCharArray());
            wr.write(new sun.misc.BASE64Encoder().encode(buf));
            wr.write("-----END CERTIFICATE-----".toCharArray());
            wr.flush();
         }
         if (args[0].equals("toder")) {
            FileOutputStream os = new FileOutputStream(args[2]);
            os.write(buf);
            os.close();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related