Saturday, 18 August 2012

AES 128-192-256 Private Key Generation in Java

Java delivers a standard tool called KeyGenerator to generate private keys. The following describes how to generate private (or symmetric) keys for AES (other algorithms are available too):
KeyGenerator kg = KeyGenerator.getInstance("AES");
SecretKey sk;

kg.init(128);
sk = kg.generateKey();
System.out.print("AES 128 - ");
System.out.println(Hex.encodeHex(sk.getEncoded()));

kg.init(192);
sk = kg.generateKey();
System.out.print("AES 192 - ");
System.out.println(Hex.encodeHex(sk.getEncoded()));

kg.init(256);
sk = kg.generateKey();
System.out.print("AES 256 - ");
System.out.println(Hex.encodeHex(sk.getEncoded()));
The generated output is:
AES 128 - 737677d940a988b04d99667406ea0d18
AES 192 - 727f44e3052aa4a6a72e385b9e9b421592f9ca1f5779925c
AES 256 - 383062669b33959fd8b57d93401c18c9d85d588ee90bb4ee82e486ac90620264
The Hex class is an Apache Commons tool.