I just started to learn cryptography. I've read a ton of articles but couldn't find a book or a course that is based on this subject (and also is not outdated).
Therefore I have a few questions (some of them were asked before but there's no specific answer).
Also i must specify that all my questions are related to aes in PHP
:
First question is what is the best way to create a completely random and unique key? So far I've made this little code that is (in my opinion) an overkill (and I guess it ads no extra security and randomness to the key since it is only 32 bytes in the end anyways) but still here it is:
$length = 32;
$hash = hash('sha512', microtime(true) . random_bytes(2) . chr(rand(0, 255)) . openssl_random_pseudo_bytes($length));
if((strlen($hash) / 2) > $length){
$x = rand($length / rand(1, $length), strlen($hash) - $length);
$key = substr($hash, $x, $length);
} else{
$key = substr($hash, 0, $length);
}
The cipher that I'm using is: aes-256-gcm
. Is there a better cipher that I could use (a more secure one that has a longer key maybe)?
Also why does aes-256-gcm
accept a longer than 32 bytes key but on decryption it just ignores anything above the first 32 bytes of that key?
Finally what is the best way to store the key for later usage (keeping in mind that I'm using php/mysql - I am aware of the fact that storing the key in the same database where you store the ciphertext/iv/tag is purely insane).
PS: I do NOT use any of these lines in any project, those are just me trying to learn.