Crypt2.SetEncodedKey – Help! I Passed a non-Hex String but Told Chilkat it was Hex

You made a mistake and set an AES encryption key in the wrong way like this:

Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
crypt.KeyLength = 256;
crypt.CryptAlgorithm = "aes";
// This is the error.  We passed base64 (or anything that is NOT a hexidecimal string)
// And then asked Chilkat to decode it as hex.
crypt.SetEncodedKey("rZFNAfY7CirLtWxKiRU187k9mqcGCBZnV4QrmBvsboE","hex");

And then we proceeded to encrypt lots of data using this key, whatever it was.

So what was the actual 32-byte key used to encrypt?

Answer:

A hex string should an even number of characters, because each byte is encoded as 2 chars. If the length of the string passed in is odd, then Chilkat assumes a leading ‘0’ was omitted. A leading 0 is prepended. For example “10203” becomes “010203”.

Chars in the range from ‘a’ to ‘f’ are converted to uppercase.

For each 2-char pair, the byte value is computed like this (in C/C++ code)

	unsigned char v, v2;
	char x = str[i];
	if (x > '9')
	    {
	    v = 10 + x - 'A';
	    }
	else
	    {
	    v = x - '0';
	    }

	v *= 16;
	x = str[i+1];
	if (x > '9')
	    {
	    v2 = 10 + x - 'A';
	    }
	else
	    {
	    v2 = x - '0';
	    }

	v += v2;
	// v is the decoded byte value.
	// Note: Because the data contains chars outside the range 0-9A-F,
	// the computation will be mod 256 (because v is an unsigned 1-byte char).

Given that the base64 string is shorter than 32 bytes (for a 256-bit key), the decoded result will not be fully 32-bytes.

Bytes having the value 0 are appended to get the full 32-byte key.

For the input: rZFNAfY7CirLtWxKiRU187k9mqcGCBZnV4QrmBvsboE, the resulting secret key in hex is: 3B3F7A127C5B8D4172CE18A4C6AC0CD38F5AE6EFCB8E00000000000000000000