I have code to run encryption and decryption, I wanna pass value from my mysql database, but it won't work
this is my code
<?php
require_once('koneksi.php');
$sql = "SELECT * from keamanan WHERE id='1'";
$r = mysqli_query($con,$sql);
//Membuat Array Kosong
$result = array();
while($row = mysqli_fetch_array($r)){
//Memasukkan Nama dan ID kedalam Array Kosong yang telah dibuat
array_push($result,array(
"iv"=>$row['kunci_pribadi'],
"key"=>$row['kunci_bersama'],
"token1"=>$row['token_lampu1'],
"token2"=>$row['token_lampu2'],
"token2"=>$row['token_lampu3'],
"token2"=>$row['token_lampu4'],
));
}
$json = json_encode(array('result'=>$result));
$data = json_decode($json);
class MCrypt
{
$iv;
$key;
function __construct()
{
$this->iv = $key;
$this->key = $iv;
}
function encrypt($str) {
//$key = $this->hex2bin($key);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($encrypted);
}
function decrypt($code) {
//$key = $this->hex2bin($key);
$code = $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata) {
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
$mcrypt = new MCrypt($data->result[0]->key,$data->result[0]->iv);
#Encrypt
$encrypted = '9975e28df055c336a9b7090b03f88689';
#Decrypt
$decrypted = $mcrypt->decrypt($encrypted);
var_dump($encrypted);
var_dump($decrypted);
?>
where I miss? I don't know my script it still can be used in php7 or not. I tried to configure what the mistake. if I write it manually the code runs fine nothing an error, but why I can't pass the value variable from my database mysql. can anyone help me?
The constructor of your class don't have entry parameters whereas you call it with parameters here
new MCrypt($data->result[0]->key,$data->result[0]->iv);
Change your __construct function to
function __construct($key, $iv)
{
$this->iv = $key;
$this->key = $iv;
}
Moreover, I suggest you to use PDO for database connection, which is considered as more secure. Maybe you could have a look at this https://phpdelusions.net/pdo
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.