6
$\begingroup$

This might be a noob question, but I couldn't find its answer anywhere online: why does an OpenSSL generated 256-bit AES key have 64 characters? The command I'm using to generate the key is:

$ openssl enc -aes-256-cbc -k secret -P -md sha1
salt=E2EE3D7072F8AAF4
key=C94A324B7221AA8A8760DA0717C80256EF4308EC6068B7144AA3BBA4A5F98007
iv =5C7CB13DBDA69B2C091E0D5E95943627

I thought I could just read the key string and base64 decode it to get a 256-bit AES key, but that didn't work because 64 characters turned into a 384-bit byte array after decoding.

/* read keyString from config... */
byte[] secretKey = Base64.getDecoder().decode(keyString);
Preconditions.checkArgument(secretKey.length == 32,
            "Length of secretKey is %s-bit instead of 256-bit: %s",secretKey.length * 8, config.getSecretKey());
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");

If I'm doing math correctly, a 256-bit key should be 41 characters in length after base64 encoding. Am I missing something obvious here?

$\endgroup$
2
  • 1
    $\begingroup$ Perfect example of a good question; You state the basic question, provide a code sample, and state why your findings prompt the question. $\endgroup$
    – Signal15
    Oct 19 '18 at 13:22
  • $\begingroup$ As answered, this is hex not b64, but b64 of 256bits would be 43 or 44 characters depending whether padding is used (like the traditional b64 in PEM, MIME, and XMLdsig/enc) or not (like the 'url-safe' b64 in JSON). OpenSSL in particular uses the PEM style of b64 (with padding). $\endgroup$ May 28 at 23:21
12
$\begingroup$

The key is hexadecimal. So every two characters makes up one hexadecimal byte, which brings the length down to 32 actual bytes. There are 8 bits per bytes, so 8*32 = 256.

$\endgroup$
1
  • $\begingroup$ Addition, for additional clarity: each of the 64 hexadecimal character encodes 4 bits. 64×4=256 bits, the key size. $\endgroup$
    – fgrieu
    May 28 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.