//George Koutsogiannakis // 2/13/2007 //every execution of this program produces a //different key because KeyGenerator uses SecureRandom //as a source of randomness import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.security.Key; public class SymmetricCryptography { public static String formatKey(Key key) { StringBuffer sb=new StringBuffer(); String algo=key.getAlgorithm(); //returns the name of the algorithm used //such as DES, DSA, RSA String fmt=key.getFormat(); //returns the encoded format of the key //such as RAW X.509 (public), PKCS#8(private) byte[] encoded=key.getEncoded(); //returns the encoded value of the key as a byte sb.append("Key{algorithm="+algo+", format="+fmt+", bytes="+encoded.length+"]\n"); if(fmt.equalsIgnoreCase("RAW")) { for(int i=0; i<=encoded.length-1; i++) { sb.append("The encoded values are:"+encoded[i]+"\n"); } } return sb.toString(); } public static void main(String[] args) { try { KeyGenerator kg=KeyGenerator.getInstance("DES"); kg.init(56); SecretKey key=kg.generateKey(); System.out.println("The key is"+"\n"+formatKey(key)); } catch(Exception e) {} } }