1

How can this be done? I want to take the resulting aes secretkey and turn it into the plaintext 16byte representation

        public SecretKey generateAesKey() throws NoSuchAlgorithmException{
                KeyGenerator keygen;
                keygen = KeyGenerator.getInstance("AES");
                keygen.init(128);
                SecretKey aesKey = keygen.generateKey();
                return aesKey;
        }

Im using this to generate the key (Pretty sure the key would be 32 bytes, unless I'm thinking of 256bit key?)

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user3746744
  • 433
  • 1
  • 4
  • 10

1 Answers1

1

SecretKey class has a method .getEncoded() which will return your key.

You can obtain your string representation in hexadecimal (for example) using the following method:

private static String bytesToHexRepresentation(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%02X ", b));
    }
    return sb.toString();
}

therefore you can do:

SecretKey myKey = generateAesKey();
byte[] encodedBytes = myKey.getEncoded();
String s = bytesToHexRepresentation(encodedBytes);
System.out.printf(s);

To print your key in a nice hexadecimal representation.

As for your second question:

  • for 128 bits the key is 16 bytes (your current case)
  • for 192 bits the key is 24 bytes
  • for 256 bits the key is 32 bytes
Flowryn
  • 1,437
  • 1
  • 16
  • 32