I have problems when encrypt the information in mySQL by using PHP. I am using below example and finally I can encrypt the content but when I am decrypt in other page, some strange words will shown.
Please help
I am using below function to encrypt
<?php
header("Content-Type:text/html; charset=utf-8");
$key = md5('test');
function encrypt($string, $key) {
$string = rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$key,$string,MCRYPT_MODE_ECB)));
return $string;
}
//connection
....
//connection
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = mysqli_real_escape_string($con,$_POST['name']);
$sql="INSERT INTO db (name) VALUES ('".encrypt($name,$key)."')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
?>
And using below function to decrypt
<?php
header("Content-Type:text/html; charset=utf-8");
$key = md5('test');
function decrypt($string, $key) {
$string = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,base64_encode($string),MCRYPT_MODE_ECB));
return $string;
}
//connection
....
//connection
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM db";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)) {
echo $row['name'] ;
echo decrypt($row['name'],$key) ;
}
?>
Input: TEST
And the result of decrypt:
K704rW4crOuvpDZe/yZ2ums0btlo8hvpeyJr91V+Ycg= x _L kR ^О dMFH 7* %Ίֶ M_< w W ^ 3M " Rk
here is an function to encrypte and decrypte string :
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
and you call it like this :
if you want to encrypt just pass it to a first param and the string in the second param like this :
$encryptedString = encrypt_decrypt('encrypt', 'test');
and to decrypte :
$decrypte = encrypt_decrypt('decrypt', $encryptedString);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.