Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.9 kB
2
Indexable
Never
<?php
include '../config/config.php';
session_start();

function decryptFile($sourceFile, $key)
{
    $encryptedData = file_get_contents($sourceFile);

    if ($encryptedData === false) {
        header('HTTP/1.1 500 Internal Server Error');
        echo 'Error reading encrypted file.';
        exit;
    }

    $iv = substr($encryptedData, 0, openssl_cipher_iv_length('aes-256-cbc'));
    $ciphertext = substr($encryptedData, openssl_cipher_iv_length('aes-256-cbc'));

    $decryptedContent = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, 0, $iv);

    if ($decryptedContent === false) {
        header('HTTP/1.1 500 Internal Server Error');
        echo 'Error decrypting file.';
        exit;
    }

    return $decryptedContent;
}

if (isset($_GET['file'])) {
    $fileToDownload = $_GET['file'];

    $encryptedFilePath = '../upload/encrypted_file/' . $fileToDownload;


    $encryptionKeyFilePath = '../../key/encryption_key.txt';
    $encryptionKey = file_get_contents($encryptionKeyFilePath);

    if ($encryptionKey === false) {
        header('HTTP/1.1 500 Internal Server Error');
        echo 'Error reading encryption key.';
        exit;
    }

    // Replace these lines with your actual logic to determine $file and $receiver
    $file = true; // Replace with your logic to determine if the file should be decrypted
    $receiver = true; // Replace with your logic to determine if the receiver is authorized

    // Check if the user is logged in
    if (isset($_SESSION['user_id'])) {
        $loggedInUserId = $_SESSION['user_id'];

        // Additional logic to check if the logged-in user is the intended receiver
        // (e.g., comparing user ID with the intended receiver ID)

        if ($file && $receiver) {
            // Decrypt the file content
            $decryptedContent = decryptFile($encryptedFilePath, $encryptionKey);

            // Set headers for downloading the decrypted content
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($fileToDownload) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . strlen($decryptedContent));

            // Output the decrypted content
            echo $decryptedContent;

            // Exit to stop further execution
            exit;
        } elseif ($file) {
            header('HTTP/1.1 403 Forbidden');
            echo 'File is encrypted because the receiver is not authorized.';
            exit;
        } else {
            header('HTTP/1.1 400 Bad Request');
            echo 'Invalid request.';
            exit;
        }
    } else {
        // Redirect to the login page if the user is not logged in
        header("Location: ../index.php");
        exit;
    }
}
?>
Leave a Comment