I learned here that it is unsafe to design encryption algorithms from scratch. Given that advice, I made a pair of encryption functions based on mcrypt:
function aes128ctr_en($data,$key,$hmac = false) {
$key = ($hmac===false) ? hash('sha256',$key,true) : hash_hmac('sha256',$key,$hmac,true);
$data .= hash('md5',$data,true);
$iv = mcrypt_create_iv(16,MCRYPT_DEV_URANDOM);
return mcrypt_encrypt('rijndael-128',$key,$data,'ctr',$iv).$iv;
}
function aes128ctr_de($data,$key,$hmac = false) {
$key = ($hmac===false) ? hash('sha256',$key,true) : hash_hmac('sha256',$key,$hmac,true);
$iv = substr($data,-16);
$data = substr($data,0,strlen($data)-16);
$data = mcrypt_decrypt('rijndael-128',$key,$data,'ctr',$iv);
$md5 = substr($data,-16);
$data = substr($data,0,strlen($data)-16);
return (hash('md5',$data,true)===$md5) ? $data : false;
}
$encrypted = aes128ctr_en('secret text','password');
echo aes128ctr_de($encrypted,'password');
- Are these safe?
- What about the IV? Is it ok to just add it to the end of the encrypted string?
- Would it be better/faster to make all this by module, that is by using
mcrypt_module_open
?
mcrypt_encrypt()
. All he's doing is wrapping it up to make it easier to use and is asking if that wrapper leads to things being less secure. I think it's reasonable to ask if this particular treatment of IVs, hashes, and key creation is done without unintentionally opening a vulnerability. \$\endgroup\$