0

Business use-case:

In my application, i allow users to upload images. Now before storing it to file system, i want images to be aes-encrypted. For displaying images in browser, i want to decrypt them on the fly in browser. So basically they will be encrypted at rest, and will be decrypted at the time of playback.

What i have implemented:

I have encrypted an image using open ssl and AES 265 CBC algorithm. Below is the command i used

openssl enc -in image-original.jpg -out image-enc.jpg -e -aes256 -k 26ca44bbeb4b6608437737970cbfe0db

On front-end, i send an HTTP call to server to read encrypted image as blob, and i try to decrypt that blob using window.crypto.subtle.decrypt function. Below is the code

window.crypto.subtle.decrypt(
        {
            name: "AES-CBC",
            length: 256
        },
        "26ca44bbeb4b6608437737970cbfe0db",
        "blob that we fetched from server"
    ).then((result) => {
        debugger;
    });

But i am getting below listed error in browser console

"TypeError: Failed to execute 'decrypt' on 'SubtleCrypto': parameter 2 is not of type 'CryptoKey'."

Questions:

I have 2 questions from you guys,

  1. Help me resolve this error, as i am not finding much help over internet
  2. Suggest me a better approach or share your experience if you have done such work in past.
Asad Ullah
  • 2,257
  • 2
  • 24
  • 23
  • 1
    The `-k` parameter in OpenSSL specifies a passphrase from which key and IV are derived, see [here](https://www.openssl.org/docs/man1.1.1/man1/openssl-enc.html), and note also the `-p` / `-P` options. You may not use the passphrase in the Web Crypto code, but instead key and IV. OpenSSL also allows you to specify key and IV _directly_, maybe this makes more sense for you. The key used in the Web Crypto code is generally a `CryptoKey` object into which the _raw_ key is imported, see [here](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/decrypt). – Topaco Aug 10 '20 at 15:49
  • @Topaco Your answer helped me alot in resolving this issue. I will be posting my complete solution here soon. – Asad Ullah Aug 13 '20 at 11:05
  • @AsadUllah, did you figure out how to fix this? – Aifos Si Prahs Jan 06 '23 at 00:32
  • @AifosSiPrahs Instead of passing raw key to window.crypto.subtle.decrypt, I had to pass CryptoKey object into which raw key was imported. – Asad Ullah Jan 07 '23 at 03:17

1 Answers1

1

Instead of passing the raw key, I had to pass CryptoKey object, in which the raw key was imported.

Asad Ullah
  • 2,257
  • 2
  • 24
  • 23