...

View Full Version : mcrypt encrypt/decrypt functions



Jak-S
02-28-2007, 01:50 PM
Hi, I have written these two functions to encrypt and then decrypt data on my site, and I was hoping someone could let me know if they are OK? I'm just not sure about the way I'm handling the IV value. Because its random, but is also required to decrypt, I'm just adding it to the encrypted string, and then splitting that in the decrypt function. Is this what most people do?


public function encrypt($string, $key) {
$mcrypt = mcrypt_module_open('rijndael-256', '', 'ofb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($mcrypt), MCRYPT_RAND);
$size = mcrypt_enc_get_key_size($mcrypt);
$key = substr(hash('sha256', $key), 0, $size);
mcrypt_generic_init($mcrypt, $key, $iv);
$encrypted = mcrypt_generic($mcrypt, $string);
mcrypt_generic_deinit($mcrypt);
mcrypt_module_close($mcrypt);
return $iv.$encrypted;
}

public function decrypt($string, $key) {
$mcrypt = mcrypt_module_open('rijndael-256', '', 'ofb', '');
$iv = substr($string, 0, mcrypt_enc_get_iv_size($mcrypt));
$string = substr($string, mcrypt_enc_get_iv_size($mcrypt));
$size = mcrypt_enc_get_key_size($mcrypt);
$key = substr(hash('sha256', $key), 0, $size);
mcrypt_generic_init($mcrypt, $key, $iv);
$decrypted = mdecrypt_generic($mcrypt, $string);
mcrypt_generic_deinit($mcrypt);
mcrypt_module_close($mcrypt);
return $decrypted;
}

Thanks, Jack

elvisismymother
02-28-2007, 03:01 PM
The Initialization Vector (IV) doesn't need to be private. In fact, as you are doing here, it can be attached to the cipher-text. Careful with those keys though. :)

Jak-S
02-28-2007, 03:08 PM
OK great, and the way I'm attaching it and then detaching it is OK? I thought I might need to use mb_substr instead of substr, but it seems to work, is this reliable enough?


Careful with those keys though.

Why? Is there a problem?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum