Is there a definied keysize to be used with the "AES_256-CBC" method in PHP, and what is the size?
Some background:
I want to store encrypted text into a PostgreSQL database. The user who posts the data has a key (stored in db) which gets appended to a generic private key hard coded in the library.
$key = $genericKey . $userKey;
The used encryption method is "AES-256-CBC" with an iv_size of 16. The IV gets prepended to the encrypted string
$return = $iv.$encrypted
This is then stored in the database.
It appears that if I produce an extremely large generic key, then store some data with $userkey1
, and then decrypt it with $userkey2
, the data just gets decoded. If I rerun it with a small generic key and small user key, it does not get decoded. To me, it looks as if the big key gets truncated somehow.
Could someone confirm this and tell me what the max keysize is? What is the best-practice to make sure the set key doesn't exceed the key_size* E.g.: md5($key)
because this produces a "fixed" amount of characters.
update
Because apparently php has its own implementation of the AES, this is the way I implement it in my own Class:
class Crypto {
function __construct(){
$this->iv_size = 16;
$this->sleutel = 'somelongkey';
$this->encryptionMethod = 'AES-256-CBC';
}
private function encrypt($str){
$sleutel = $this->sleutel . $this->userKey;
$iv = $this->generateRandomString($this->iv_size);
$cipher = openssl_encrypt($str, $this->encryptionMethod, $sleutel, 0, $iv);
return $iv.$cipher;
}
public function decrypt($data){
$iv = substr($data, 0, $this->iv_size);
$sleutel = $this->sleutel . $this->userKey;
return openssl_decrypt(substr($data, $this->iv_size), $this->encryptionMethod, $sleutel, 0, $iv);
}
}