Are there any security flaws in what I plan to do?
I need to store the following in my DB:
- a random string to act as a salt for encrypting a password
- the encrypted password that used the salt in #1
Here's the PHP code I have to accomplish the above tasks:
<?php
function decrypt($string, $encryption_key = '')
{
$initialization_vector = get_initialization_vector();
// Convert hexadecimal data into binary representation
$string = hex2bin($string);
// See: http://php.net/manual/en/mcrypt.ciphers.php
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $string, MCRYPT_MODE_ECB, $initialization_vector));
}
function encrypt($string, $encryption_key = '')
{
$initialization_vector = get_initialization_vector();
// See: http://php.net/manual/en/mcrypt.ciphers.php
$string = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $string, MCRYPT_MODE_ECB, $initialization_vector);
// Convert binary data into hexadecimal representation
$string = bin2hex($string);
return $string;
}
function get_initialization_vector()
{
// See: http://php.net/manual/en/mcrypt.ciphers.php
// MCRYPT_BLOWFISH selected as it appears to be one of the "universally"
// supported ciphers supported by the mcrypt extension
$initialization_vector_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
// See: http://php.net/manual/en/function.mcrypt-create-iv.php
// The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM
// (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom).
// Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.
$initialization_vector = mcrypt_create_iv($initialization_vector_size, MCRYPT_RAND);
return $initialization_vector;
}
function get_random_string($character_set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', $minimum_length = 8, $maximum_length = 12)
{
if ($minimum_length > $maximum_length)
{
$length = mt_rand($maximum_length, $minimum_length);
}
else
{
$length = mt_rand($minimum_length, $maximum_length);
}
$random_string = '';
for ($i = 0; $i < $length; $i++)
{
$random_string .= $character_set[(mt_rand(0, (strlen($character_set) - 1)))];
}
return $random_string;
}
function hex2bin($hexadecimal_data)
{
$binary_representation = '';
for ($i = 0; $i < strlen($hexadecimal_data); $i += 2)
{
$binary_representation .= chr(hexdec($hexadecimal_data{$i} . $hexadecimal_data{($i + 1)}));
}
return $binary_representation;
}