I am using aes256 with php to encrypt data.
In the various documents I see various ways to generate a key, Like:
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
Or
$Key = "what ever, plain string";
Or
$Key = "123456789abcdef";//128bit
What is the point of the first example, as opposed to the others? Why not simply use a random string, 128 or 256 long?
I am using the example here http://php.net/manual/en/function.mcrypt-encrypt.php with each of the different key generating methods above.
You have three different key lengths. AES is specified for the following three key lengths: 128-bit (16 byte), 192-bit (24 byte) and 256-bit (32 byte). I'm not going to go into detail about the strength of different key sizes.
Let's take them apart:
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
This is a hex encoded which is 64 characters long in encoded form. The key itself will be 32 bytes long which means that when the key is passed to mcrypt_encrypt()
AES-256 is used automatically.
$Key = "what ever, plain string";
This is a 23 character string which can be used as a key for PHP versions before 5.6.0. This is not a valid length for a key in AES. MCrypt will pad the key with \0
up to the next valid key size which is 24 byte for AES-192. So this key is actually a valid key for PHP 5.6 in this form:
$Key = "what ever, plain string\0";
$Key = "123456789abcdef"; //128bit
This is a 15 character "key". As with the previous example, it will be padded to reach 16 bytes so that AES-128 is used.
Since you're asking about key generation, this question contains some approaches. Keys should be random and consist of all possible bytes. Using keys that are only alphanumeric or only contain printable characters is not good if you want to be safe against brute-force attacks on your key.
Since it's not possible to directly hard-code arbitrary bytes as a key in a code file, you should use the first approach of hard-coding an encoded version of the key and decode it programmatically.
There are only a handful of scenarios where hard-coding a symmetric key in the code can be used:
If your scenario doesn't match to the above, you're either happy with obfuscation or you should think about how you can employ public-key-encryption with a hybrid encryption approach.