1 /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
2 /**
3  * This progam will demonstrate the DSA keypair generation.
4  *   $ CLASSPATH=.:../build javac KeyGen.java
5  *   $ CLASSPATH=.:../build java KeyGen rsa output_keyfile comment
6  * or
7  *   $ CLASSPATH=.:../build java KeyGen dsa output_keyfile comment
8  * You will be asked a passphrase for output_keyfile.
9  * If everything works fine, you will get the DSA or RSA keypair,
10  * output_keyfile and output_keyfile+".pub".
11  * The private key and public key are in the OpenSSH format.
12  *
13  */
14 import com.jcraft.jsch.*;
15 import javax.swing.*;
16 
17 class KeyGen{
main(String[] arg)18   public static void main(String[] arg){
19     int key_size = 1024;
20     if(arg.length<3){
21       System.err.println(
22 "usage: java KeyGen rsa output_keyfile comment\n"+
23 "       java KeyGen dsa output_keyfile comment\n"+
24 "       java KeyGen ecdsa-sha2-256 output_keyfile comment\n"+
25 "       java KeyGen ecdsa-sha2-384 output_keyfile comment\n"+
26 "       java KeyGen ecdsa-sha2-521 output_keyfile comment");
27       System.exit(-1);
28     }
29     String _type=arg[0];
30     int type=0;
31     if(_type.equals("rsa")){type=KeyPair.RSA;}
32     else if(_type.equals("dsa")){type=KeyPair.DSA;}
33     else if(_type.equals("ecdsa-sha2-nistp256")){
34       type=KeyPair.ECDSA;
35       key_size=256;
36     }
37     else if(_type.equals("ecdsa-sha2-nistp384")){
38       type=KeyPair.ECDSA;
39       key_size=384;
40     }
41     else if(_type.equals("ecdsa-sha2-nistp521")){
42       type=KeyPair.ECDSA;
43       key_size=521;
44     }
45     else {
46       System.err.println(
47 "usage: java KeyGen rsa output_keyfile comment\n"+
48 "       java KeyGen dsa output_keyfile comment\n"+
49 "       java KeyGen ecdsa-sha2-256 output_keyfile comment\n"+
50 "       java KeyGen ecdsa-sha2-384 output_keyfile comment\n"+
51 "       java KeyGen ecdsa-sha2-521 output_keyfile comment");
52       System.exit(-1);
53     }
54     String filename=arg[1];
55     String comment=arg[2];
56 
57     JSch jsch=new JSch();
58 
59     String passphrase="";
60     JTextField passphraseField=(JTextField)new JPasswordField(20);
61     Object[] ob={passphraseField};
62     int result=
63       JOptionPane.showConfirmDialog(null, ob, "Enter passphrase (empty for no passphrase)",
64 				    JOptionPane.OK_CANCEL_OPTION);
65     if(result==JOptionPane.OK_OPTION){
66       passphrase=passphraseField.getText();
67     }
68 
69     try{
70       KeyPair kpair=KeyPair.genKeyPair(jsch, type, key_size);
71       kpair.setPassphrase(passphrase);
72       kpair.writePrivateKey(filename);
73       kpair.writePublicKey(filename+".pub", comment);
74       System.out.println("Finger print: "+kpair.getFingerPrint());
75       kpair.dispose();
76     }
77     catch(Exception e){
78       System.out.println(e);
79     }
80     System.exit(0);
81   }
82 }
83