opensslaesencryption-symmetricsubtlecrypto

Decrypt AES encrypted image in browser using window.crypto.subtle.decrypt


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.

Solution

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