I want to encrypt password to prevent SQL injection and other attacks and I used an encryption function in PHP, but I don't know how to use it to encrypt passwords.
I want each password in the user table to be encrypted so i can connect to the database and use a query but it doesn't work.
Can anyone help me please?
ecnription.php
<?php
require_once('include/connect.php');
if(isset($_SESSION['user_id']))
{
$id= $_SESSION['user_id'];
}
$sql = mysql_query("SELECT password FROM user WHERE user_id= '$id'")or die(mysql_error());
while($row = mysql_fetch_array($sql))
{
$enc_pass= $row['password'];
}
error_reporting(0);
class Encryption
{
const CYPHER = MCRYPT_RIJNDAEL_256;
const MODE = MCRYPT_MODE_CBC;
const KEY = 'somesecretphrase';
public function encrypt($plaintext)
{
$td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, self::KEY, $iv);
$crypttext = mcrypt_generic($td, $plaintext);
mcrypt_generic_deinit($td);
return base64_encode($iv.$crypttext);
}
public function decrypt($crypttext)
{
$crypttext = base64_decode($crypttext);
$plaintext = '';
$td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($crypttext, 0, $ivsize);
$crypttext = substr($crypttext, $ivsize);
if ($iv)
{
mcrypt_generic_init($td, self::KEY, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return trim($plaintext);
}
}
$encrypted_string = Encryption::encrypt($enc_pass);
$decrypted_string = Encryption::decrypt($encrypted_string);
echo $encrypted_string . "<br>" . PHP_EOL;
var_dump($id);
echo $decrypted_string . "<br>" . PHP_EOL;