1 /*
2  * @(#) $Id: GenKCommand.java,v 1.2 2003/07/08 08:13:53 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10 package org.jstk.crypt;
11
12import java.util.*;
13import java.security.*;
14import java.io.*;
15import javax.crypto.SecretKey;
16import javax.crypto.KeyGenerator;
17
18import org.jstk.*;
19
20public class GenKCommand extends JSTKCommandAdapter{
21    private static HashMap defaults = new HashMap();
22    static {
23        defaults.put("algorithm", "DES");
24        defaults.put("keysize", "56");
25        defaults.put("action", "discard");
26        defaults.put("file", "my.secretkey");
27        defaults.put("keystore", "my.keystore");
28        defaults.put("storepass", "changeit");
29        defaults.put("kstype", "JCEKS");
30        defaults.put("alias", "mykey");
31    }
32    public String briefDescription(){
33        return "generates a secret key ( for symmetric algorithms )";
34    }
35
36    public String[] useForms(){
37        String[] forms = {
38            "[-algorithm <alg> -keysize <keysize>] [-action\n" +
39            "\t(print|discard)] [-provider <provider>]",
40            "[-algorithm <alg> -keysize <keysize>] [-action save\n" +
41            "\t[-file <filename>]] [-provider <provider>]",
42            "[-algorithm <alg> -keysize <keysize>] [-action store\n" +
43            "\t[-keystore <keystore>] [-kstype (JCEKS|JKS)] [-storepass <storepass>]\n" +
44            "\t[-alias <alias>] [-keypass <keypass>]] [-provider <provider>]"
45        };
46        return forms;
47    }
48
49    public String optionsDescription(){
50        return
51            "  -action <action>    : what to do with the key?(print|store|save|discard).[" +
52            defaults.get("action") + "]\n" +
53            "  -file <filename>    : where to save the serialized key?[" +
54            defaults.get("filename") + "]\n" +
55            "  -keystore <keystore>: where to store the key?[" +
56            defaults.get("keystore") + "]\n" +
57            "  -kstype <kstype>    : keystore type.[" +
58            defaults.get("kstype") + "]\n" +
59            "  -storepass <storepass>: Password for keystore.[" +
60            defaults.get("storepass") + "]\n" +
61            "  -alias <alias>      : alias to access the key in the keystore.[" +
62            defaults.get("alias") + "]\n" +
63            "  -keypass <keypass>  : Password for key in the keystore.[" +
64            defaults.get("keypass") + "]\n" +
65            "  -keysize <keysize>  : Key size (in bits).[" +
66            defaults.get("keysize") + "]\n" +
67            "  -algorithm <alg>    : Algorithm for secret key generator.[" +
68            defaults.get("algorithm") + "]\n" +
69            "  -provider <provider>: provider name for KeyGenerator.\n";
70    }
71
72    public String[] sampleUses(){
73        String[] uses = {
74            "",
75            "-algorithm DESede -keysize 112 -action print",
76            "-action store -keystore test.ks -storepass changeit -alias testkey1",
77            "-action save -file test1.key"
78        };
79        return uses;
80    }
81    public Object execute(JSTKArgs args) throws JSTKException{
82        try {
83            args.setDefaults(defaults);
84            String providerName = args.get("provider");
85            String algorithm = args.get("algorithm");
86            String keysizeString = args.get("keysize");
87            int keysize = Integer.parseInt(keysizeString);
88            String action = args.get("action");
89
90            KeyGenerator kg;
91            if (providerName != null)
92                kg = KeyGenerator.getInstance(algorithm, providerName);
93            else
94                kg = KeyGenerator.getInstance(algorithm);
95
96            kg.init(keysize, new SecureRandom());
97            SecretKey key = kg.generateKey();
98
99            if (action.equals("discard")){
00                return new JSTKResult(key, true, "Secret Key generated");
01            } else if (action.equals("save")){  // Save the serialized object in a file
02                String fileName = args.get("file");
03                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
04                oos.writeObject(key);
05                oos.close();
06                return new JSTKResult(key, true, "SecretKey written to file: " + fileName);
07            } else if (action.equals("store")){ // Store the key in a keystore
08                String keystore = args.get("keystore");
09                String storepass = args.get("storepass");
10                String kstype = args.get("kstype");
11
12                String keypass = args.get("keypass");
13                if (keypass == null)
14                    keypass = storepass;
15                String alias = args.get("alias");
16
17                KeyStore ks;
18                if (providerName != null)
19                    ks = KeyStore.getInstance(kstype, providerName);
20                else
21                    ks = KeyStore.getInstance(kstype);
22
23                FileInputStream fis;
24                try {
25                    fis = new FileInputStream(keystore);
26                    ks.load(fis, storepass.toCharArray());
27                    fis.close();
28                } catch (IOException ioe){  // File cannot be open for reading.
29                    ks.load(null, storepass.toCharArray());
30                }
31
32                ks.setKeyEntry(alias, key, keypass.toCharArray(), null);
33                FileOutputStream fos = new FileOutputStream(keystore);
34                ks.store(fos, storepass.toCharArray());
35                return new JSTKResult(key, true, "SecretKey stored to keystore \"" +
36                                        keystore + "\" with alias: " + alias);
37            } else if (action.equals("print")){
38                return new JSTKResult(key, true, KeyUtil.format(key, "SecretKey"));
39            }
40            return new JSTKResult(null, false, "unknown action: " + action);
41        } catch (Exception exc){
42            throw new JSTKException("GenKCommand.execute() failed", exc);
43        }
44    }
45
46    public static void main(String[] args) throws Exception {
47        JSTKOptions opts = new JSTKOptions();
48        opts.parse(args, 0);
49        GenKCommand genKCmd = new GenKCommand();
50        JSTKResult result = (JSTKResult)genKCmd.execute(opts);
51        System.out.println(result.getText());
52        System.exit(result.isSuccess()? 0 : 1);
53    }
54}