1 /*
2  * @(#) $Id: GenerateSecretKey.java,v 1.2 2003/07/08 08:13:52 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  */
10import javax.crypto.KeyGenerator;
11import javax.crypto.SecretKey;
12import java.security.Key;
13
14public class GenerateSecretKey {
15    private static String formatKey(Key key){
16        StringBuffer sb = new StringBuffer();
17        String algo = key.getAlgorithm();
18        String fmt = key.getFormat();
19        byte[] encoded = key.getEncoded();
20        sb.append("Key[algorithm=" + algo + ", format=" + fmt + ", bytes=" + encoded.length + "]\n");
21        if (fmt.equalsIgnoreCase("RAW")){
22            sb.append("Key Material (in hex):: ");
23            sb.append(Util.byteArray2Hex(key.getEncoded()));
24        }
25        return sb.toString();
26    }
27    public static void main(String[] unused) throws Exception {
28        KeyGenerator kg = KeyGenerator.getInstance("DES");
29        kg.init(56); // 56 is the keysize. Fixed for DES
30        SecretKey key = kg.generateKey();
31        System.out.println("Generated Key:: " + formatKey(key));
32    }
33}