-2

Hi I have a posted data (firstname, lastname, birthdate, phone etc)being encrypted by a php function called encryptthis (loaded from functions.php)into a mysql database.

The end user then needs to retrieve records via a php form using on the email col in the database. $email = $_POST['email'] - Search for all records that match

For this reason the email col is not encrypted. I therefore did a pre-query selecting the records where addedby_email = $email then I looped through the encrypted fields decrypting them with my decryptthis function. I have tried to do this without the prequery but keep getting a null result / json response. Looking at my code below can you suggest how i can return decrypted records without the prequery?

Functions being used to encrypt / decrypt

<?php
include '../../key.php';
//ENCRYPT FUNCTION
function encryptthis($data, $key) {
$encryption_key = base64_decode($key);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
return base64_encode($encrypted . '::' . $iv);
}

//DECRYPT FUNCTION
function decryptthis($data, $key) {
$encryption_key = base64_decode($key);
list($encrypted_data, $iv) = array_pad(explode('::', base64_decode($data), 2),2,null);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
}

?>

Get records code

<?php
include './functions.php';
include './enc_config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Find the required post values
    $table = $_POST['appurlkey'];
    $email = $_POST['email'];
            
    try {
        // Start connection
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // Set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    //Pre-Query in order to decrypt 
        $result = $conn->query("SELECT * FROM `patient_$table` WHERE `addedby_email`= '$email'") ;
    
    //loop through the encrypted fields and pass them to a new variable
    while( $row = $result->fetch(PDO::FETCH_ASSOC))
        {
        $addedby_name = decryptthis($row['addedby_name'], $key);
        $firstname = decryptthis($row['firstname'], $key);
        $lastname = decryptthis($row['lastname'], $key);
        $birthdate = decryptthis($row['birthdate'], $key);
        $phone = decryptthis($row['phone'], $key);
        $address= decryptthis($row['address'], $key);
        $postcode = decryptthis($row['postcode'], $key);
        }
        
        
    // Original Query with decrypted values being posted in the $data array
    $sql = "SELECT * FROM patient_$table WHERE addedby_email=:addedby_email AND active=:active ORDER BY id DESC";


        
        // Prepare query
        $stmt = $conn->prepare($sql);
        
        // Bind
        $stmt->bindValue(':addedby_email', $email);
        $stmt->bindValue(':active',  '1');
        
        // Execute
        $stmt->execute();
        
        if ($stmt->rowCount() > 0) {
            
            $msg = "Successfully fetched the patients list.";
            
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach($rows as $row) {
                
                $myDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $row["created_at"]);
                $created_at = $myDateTime->format('d/m/Y');
                
                $data = [
                    "id" => $row["id"],
                    "addedby_email" => $row["addedby_email"],
                    "addedby_name" => $addedby_name,
                    "firstname" => $firstname,
                    "lastname" => $lastname,
                    "birthdate" => $birthdate,
                    "phone" => $phone,
                    "email" => $row["email"],
                    "address" => $address,
                    "town" => $row["town"],
                    "county" => $row["county"],
                    "postcode" => $postcode,
                    "patient_type" => $row["patient_type"],
                    "doctor" => $row["doctor"],                    
                    "active" => $row["active"],
                    "created_at" => $created_at
                ];  
                
                $patients[] = [
                    "pt_id" => $row["id"],
                    "name" => $firstname . " " . $lastname,
                    "birthdate" => $birthdate,
                    "data" => $data,
                ];
?>
OnTarget
  • 27
  • 7
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman May 20 '22 at 11:15

0 Answers0