0

I want to encrypt a file in PHP serverside and decrypt it on the client using javascript.

So far I have been able to do this in PHP:

ENCRYPT


function encryptFile($path, $key)
{
    $iv = openssl_random_pseudo_bytes(16);
    $encrypted = openssl_encrypt(file_get_contents($path), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($iv . $encrypted);
}

public function downloadEncryptedFile()
{
    $key = 'fee-fi-fum';
    $path = storage_path('app/public/nicesong.mp3');
    $encrypted = encryptFile($path, $key);
    return response($encrypted, 200, [
        'Content-Type' => 'application/octet-stream',
        'Content-Disposition' => 'attachment; filename="your-file.encrypted"'
    ]);
}

The server endpoint calls the downloadEncryptedFile() method which in turn returns a response with an application/octet-stream Content-Type header.

How do I implement decryption on the client side.

3m1n3nc3
  • 353
  • 7
  • 21
  • What's the server side endpoint - what does it send to the client? Which type of encryption? – Thomas Frank May 04 '23 at 03:29
  • The endpoint calls the downloadEncryptedFile() method which returns a response with an `application/octet-stream` Content-Type header, the encryption is done on open ssl aes-256-cbc – 3m1n3nc3 May 04 '23 at 03:37
  • send the file from BE as string, decode it in JS then download it. – marius-ciclistu May 06 '23 at 21:23
  • @marius-ciclistu The file has already been encrypted, from the Backend and is being sent as a string already. The question is, how do I decrypt it in Javascript? – 3m1n3nc3 May 07 '23 at 08:01
  • Google js base 64 decode and then the ssl decription. Then google how to download binary string to file in js. You send the file in FE as download. send it as json with a key – marius-ciclistu May 07 '23 at 12:15
  • https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript – marius-ciclistu May 07 '23 at 13:24
  • https://stackoverflow.com/questions/76172707/encrypt-and-decrypt-using-crypto-js-similar-to-openssl-function-in-php – marius-ciclistu May 07 '23 at 18:34

0 Answers0