//package de.stephanwiesner.security;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;


/*
   A simple GUI for entering the needed information
   to generate certificates. <br>
   Generates a keystore file containing the private key
   as well as the public certificate.<br>

   @version 1.0
   @date 02.08.2001
   @author stephan@stephanwiesner.de
*/
public class KeytoolManager extends JFrame  implements ActionListener
{
   // SWING Komponenten
      Container hintergrund;
      Color labelFarbe = new Color(113, 115, 224);
      JTextField dateiField, aliasField, cnField, ouField, oField, lField, sField;
      JTextField cField, alField, kpField, spField, exField;




   /**
      Displays the informations of a certificate <br>
   */
   public void getInformation(String dateiName)
   {
      try
      {
         // Get the correct certificate factory.
         CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
         // Each file specified on the command line must contain a single
         // DER-encoded X.509 certificate. The DER-encoded certificate
         // can be in either binary or ASCII format.
         for (int i = 0; i < arstring.length; i++)
         {
           // Open the file.
           FileInputStream fileinputstream = new FileInputStream(arstring[i]);
           // Generate a certificate from the data in the file.
           X509Certificate x509certificate =
             (X509Certificate)certificatefactory.generateCertificate(fileinputstream);
           // First, let's print out information about the certificate itself.
           System.out.println("---Certificate---");
           System.out.println("type = " + x509certificate.getType());
           System.out.println("version = " + x509certificate.getVersion());
           System.out.println("subject = " + x509certificate.getSubjectDN().getName());
           System.out.println("valid from = " + x509certificate.getNotBefore());
           System.out.println("valid to = " + x509certificate.getNotAfter());
           System.out.println("serial number = " + x509certificate.getSerialNumber().toString(16));
           System.out.println("issuer = " + x509certificate.getIssuerDN().getName());
           System.out.println("signing algorithm = " + x509certificate.getSigAlgName());
           System.out.println("public key algorithm = " + x509certificate.getPublicKey().getAlgorithm());
           // Next, let's print out information about the extensions.
           System.out.println("---Extensions---");
           Set setCritical = x509certificate.getCriticalExtensionOIDs();
           if (setCritical != null && setCritical.isEmpty() == false)
             for (Iterator iterator = setCritical.iterator(); iterator.hasNext(); )
               System.out.println(iterator.next().toString() + " *critical*");
           Set setNonCritical = x509certificate.getNonCriticalExtensionOIDs();
           if (setNonCritical != null && setNonCritical.isEmpty() == false)
             for (Iterator iterator = setNonCritical.iterator(); iterator.hasNext(); )
               System.out.println(iterator.next().toString());
           // We're done.
           System.out.println("---");
           // Close the file.
           fileinputstream.close();
         }
       }
       catch (Exception exception)
       {
         exception.printStackTrace();
       }
  }// getInformation()



   private int doIT(String s) throws Exception
   {
      System.out.println(s);
      Process p = Runtime.getRuntime().exec("cmd /c " + s);
      InputStream stderr = p.getErrorStream();
      InputStreamReader isr = new InputStreamReader(stderr);
      BufferedReader br = new BufferedReader(isr);

      String line = null;
      while ( (line = br.readLine()) != null)
         System.out.println(line);
      int exitVal = p.waitFor();
      System.out.println("Process exitValue (!=0 means Error): " + exitVal + "\n");

      if(exitVal != 0)
      {
         pr("Make sure you don't have an old keystore with the same name lying around here.");
         fehler("There is an error, take a look at the commandline for more information");
      }
      return exitVal;
   } // do IT()


   private void pr(String s)
   {
      System.out.println(s);
   }


   private void meldung(String s)
   {
      System.out.println(s);
      JOptionPane.showMessageDialog(this, s);
   }


   private void fehler(String s)
   {
      System.out.println(s);
      JOptionPane.showMessageDialog(this, s);
      //System.exit(1);
   }




   public void actionPerformed(ActionEvent ev)
   {
  	   Object source=ev.getSource();
	   // System.out.println("Ein Event:"+ev.getActionCommand().toString());
	   String event=ev.getActionCommand();

	   if(event == "start")
	   {
         pr("Starting to generate key . . .");
         try {
            String s = "keytool -genkey";

            s += " -alias "     + aliasField.getText();
            s += " -dname \"CN="
              + cnField.getText() + ", OU=" + ouField.getText() + ", O=" + oField.getText()
              + ", L=" + lField.getText() + ", S=" + sField.getText() + ", C=" + cField.getText() + "\"";
            s += " -keyalg "    + alField.getText();
            s += " -keypass "   + kpField.getText();
            s += " -storepass " + spField.getText();
            s += " -validity "  + exField.getText();
            s += " -keystore "  + dateiField.getText() + ".keystore";

            if(doIT(s) == 0)
            {
               pr("Now generating the certificate . . .");
               s = "keytool -export";
               s += " -alias "     + aliasField.getText();
               s += " -storepass " + spField.getText();
               s += " -file " + dateiField.getText() + ".cer";
               s += " -keystore "  + dateiField.getText() + ".keystore";
               doIT(s);
            }


            pr("\nNow testing the certificate . . .");
            getInformation(dateiField.getText() + ".cer");

            pr("\nReady, over and out :-)");


         }catch(Exception e) { fehler(""+e);}
	 	   pr("Okay, done.");
	 	   return;
	   }
   }// action()




   public KeytoolManager()
   {
      super("Keytool Manager - by www.stephanwiesner.de");

      hintergrund = getContentPane();
      hintergrund.setLayout( new GridLayout(13, 2) );
      //hintergrund.setBounds(0,0,800, 600);
      hintergrund.setBackground( labelFarbe );
      addWindowListener(new WindowAdapter()   { public void windowClosing(WindowEvent e) {  System.exit(0); } });

      // Labels + TextFields
         JLabel dateiLabel = new JLabel("File");
            hintergrund.add(dateiLabel);
         dateiField = new JTextField("key");
            hintergrund.add(dateiField);

         JLabel aliasLabel = new JLabel("Alias");
            hintergrund.add(aliasLabel);
         aliasField = new JTextField("SToffel");
            hintergrund.add(aliasField);

         JLabel cnLabel = new JLabel("Computername:");
            hintergrund.add(cnLabel);
         cnField = new JTextField("www.stephanwiesner.de");
            hintergrund.add(cnField);

         JLabel ouLabel = new JLabel("Department:");
            hintergrund.add(ouLabel);
         ouField = new JTextField("Programming and Design");
            hintergrund.add(ouField);

         JLabel oLabel = new JLabel("Company:");
            hintergrund.add(oLabel);
         oField = new JTextField("SToffel AG");
            hintergrund.add(oField);

         JLabel lLabel = new JLabel("City:");
            hintergrund.add(lLabel);
         lField = new JTextField("Lüneburg");
            hintergrund.add(lField);

         JLabel sLabel = new JLabel("State:");
            hintergrund.add(sLabel);
         sField = new JTextField("Niedersachsen");
            hintergrund.add(sField);

         JLabel cLabel = new JLabel("Country");
            hintergrund.add(cLabel);
         cField = new JTextField("de");
            hintergrund.add(cField);

         JLabel alLabel = new JLabel("Algorythm:");
            hintergrund.add(alLabel);
         alField = new JTextField("RSA");
            hintergrund.add(alField);

         JLabel kpLabel = new JLabel("KeyPassword:");
            hintergrund.add(kpLabel);
         kpField = new JTextField("123456");
            hintergrund.add(kpField);

         JLabel spLabel = new JLabel("StorePassword:");
            hintergrund.add(spLabel);
         spField = new JTextField("123456");
            hintergrund.add(spField);

         JLabel exLabel = new JLabel("Expires:");
            hintergrund.add(exLabel);
         exField = new JTextField("90");
            hintergrund.add(exField);



      // Die Buttons
         JLabel l1 = new JLabel("Press to Generate");
            hintergrund.add(l1);
         JButton startButton = new JButton("Start");
            startButton.addActionListener(this);
            startButton.setActionCommand("start");
            hintergrund.add(startButton);


      // Anzeigen
         this.addWindowListener(new WindowAdapter()   { public void windowClosing(WindowEvent e)
         {  System.out.println("Auf Wiedersehen . . ."); System.exit(0); } });


         this.setLocation(5, 5);
         this.setSize(300, 400);
         this.setVisible(true);

   }// Konstruktor()




   public static void main(String[] args)
   {
      KeytoolManager k = new KeytoolManager();
   }// main()

}// class


