Saturday 12 January 2008

DES, String, byte and KeySpec

I was given a small task to extract two secret keys from a String of length 32 in hexadecimal format:

String keydata = "BB3F730E11F4F02CC4EFB8FF18AF37AA";

The two keys were of length 16:

String left = keydata.substring(0, 16);
String right = keydata.substring(16, 32);

Using Apache Codec, extract the byte data:

byte[] leftKey = Hex.decodeHex(left.toCharArray());
byte[] rightKey = Hex.decodeHex(right.toCharArray());

And finally, get the cipher:

Cipher cipher = Cipher.getInstance("DES");
DESKeySpec desKeySpec = new DESKeySpec(leftKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(desKeySpec.getKey(), "DES");

And finally, init the cipher:

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

No comments:

Blog Archive