-1

I need help doing this chat app, i already encrypted the sign up password and the login password with pass_hash. Now i need help encrypting the messages witch is really hard form my coding knowlege at the moment. What i want to do is that the messages be encrypted on the DataBase and its not necessary encrypted in transint. If someone could help me i would be thankful! I alredy try make this code but returns empty on chat and i dont kow why.

insert-chat

<?php 
    session_start();
    if(isset($_SESSION['unique_id'])){
        include_once "config.php";
        $outgoing_id = $_SESSION['unique_id'];
        $incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']);
        $message = mysqli_real_escape_string($conn, $_POST['message']);
        $message_to_encrypt = $message;
        $secret_key = 'mysecretkey' ;
        $method = "aes128";
        $iv_length = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($iv_length);

        $encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);

        if(!empty($message)){
            $sql = mysqli_query($conn, "INSERT INTO messages (incoming_msg_id, outgoing_msg_id, msg)
                                        VALUES ({$incoming_id}, {$outgoing_id}, '{$encrypted_message}')") or die();
        }
    }else{
        header("location: ../login.php");
    }


    
?>

get-chat

<?php 
    session_start();
    if(isset($_SESSION['unique_id'])){
        include_once "config.php";
        $outgoing_id = $_SESSION['unique_id'];
        $incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']);
        $output = "";
        $sql = "SELECT * FROM messages LEFT JOIN users ON users.unique_id = messages.outgoing_msg_id
                WHERE (outgoing_msg_id = {$outgoing_id} AND incoming_msg_id = {$incoming_id})
                OR (outgoing_msg_id = {$incoming_id} AND incoming_msg_id = {$outgoing_id}) ORDER BY msg_id";
        $query = mysqli_query($conn, $sql);
        
        $message_to_encrypt = $row['msg'] ;
        $secret_key = "mysecretkey";
        $method = "aes128";
        $iv_length = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($iv_length);
        $encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);

        $decrypted_message = openssl_decrypt($encrypted_message, $method, $secret_key, 0, $iv);

        if(mysqli_num_rows($query) > 0){
            while($row = mysqli_fetch_assoc($query)){
                if($row['outgoing_msg_id'] === $outgoing_id){
                    $output .= '<div class="chat outgoing">
                                <div class="details">
                                    <p>'.$row['msg']  .'</p>
                                </div>
                                </div>';
                }else{
                    $output .= '<div class="chat incoming">
                                <img src="php/images/'.$row['img'].'" alt="">
                                <div class="details">
                                    <p>'.$row['msg'].'</p>
                                </div>
                                </div>';
                }
            }
        }else{
            $output .= '<div class="text">Sem mensagens disponiveis.Envie uma agora :)</div>';
        }
        echo $output;
    }else{
        header("location: ../login.php");
    }

?>

chat

source code git hub

Raam
  • 1
  • 1
  • Are the values correct before you try to insert them? Are they getting into the database correctly but not being extracted and displayed properly? Precisely which part of your code isn't working when you debug it? – droopsnoot Dec 13 '21 at 09:25
  • I don't understand why you retrieve a (presumably) encrypted message from your database, encrypt it again, then decrypt the message you just encrypted. Then, you do nothing with those variables and just display the `msg` column from the database. Surely all you need to do it retrieve it, decrypt it, then display the decrypted message? – droopsnoot Dec 13 '21 at 09:27
  • You also need to read up on Prepared Statements instead of concatenating strings into your queries like that, for all sorts of reasons. I don't do encryption, but if there's a chance the encrypted string might contain a single-quote, your query will fail with a syntax error as it's written here. – droopsnoot Dec 13 '21 at 09:29
  • the user wtites a message that will be encrypted into the data base (msg) then in the code "get-chat.php" does the reasearch in the database and writes the values (msg), but the problem is that i want that the message appears deincrypted only in the user display – Raam Dec 13 '21 at 09:39
  • **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/5741187) – Dharman Dec 13 '21 at 09:53
  • OK, the code just needs to retrieve the message from the database, decrypt it, then display the decrypted string. Lose the code in `get_chat.php` that encrypts the message after retrieving it, change your call to `openssl_decrypt()` so that it works on `$row['msg']`, then display the decrypted string. – droopsnoot Dec 13 '21 at 18:10

1 Answers1

-1

you can use AES_DECRYPT() and AES_ENCRYPT() in Mysql to encrypt & decrypt any data that you want. see more here

  • i'm gonna try but where i put AES_ENCRYPT() on // VALUES ({$incoming_id}, {$outgoing_id}, '{$encrypted_message}')") or die();// ? – Raam Dec 13 '21 at 11:05
  • at first define a KEY then create a sql like this : "INSERT INTO chats (incoming_id,outgoing_id,encrypted_message) VALUES ($incoming_id','$outgoing_id',AES_ENCRYPT('$encrypted_message','".KEY."'));"; – Arash Abedi Dec 13 '21 at 11:33