brix / crypto-js

JavaScript library of crypto standards.
Other
15.87k stars 2.39k forks source link

Encrypting and decrypting pdf files. #451

Open nalnir opened 1 year ago

nalnir commented 1 year ago

I am trying to find the way how to encrypt and decrypt pdf file. I have a encrypt function:

export const encryptDocument = async (password: string, document: Blob) => {
    return new Promise<CryptoJS.lib.CipherParams>((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = () => {
            // Convert the file content to binary data
            const binaryData = fileReader.result as ArrayBuffer;

            const uint8Array = new Uint8Array(binaryData);
            const array = Array.from(uint8Array, (byte) => byte);

            // Encrypt the binary data using CryptoJS
            const encryptedData = CryptoJS.AES.encrypt(
                CryptoJS.lib.WordArray.create(array),
                password
            )

            // Return the encrypted data
            resolve(encryptedData);
        };
        fileReader.onerror = (event) => {
            reject(event.target?.error);
        };
        fileReader.readAsArrayBuffer(document);
    });
}

And then I want to decrypt it and download it

const password = 'test'
const decryptedData = CryptoJS.AES.decrypt(doc, password).toString(CryptoJS.enc.Latin1);

const decryptedBlob = new Blob([decryptedData], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = URL.createObjectURL(decryptedBlob);
link.download = 'testing';
link.click();

But I the downloaded pdf file is corrupted or empty and I am not able to open it at all.

When I console log the encryptedData.toString() I get something like this: U2FsdGVkX19UTadvO67I4hsuI+deTOVQKCelKM1B5rvRtCL67GnYrP09... and the string just goes on which seems like it's correct.

When I console log decryptedData i get something like this (I had to upload the photo because when pasting it as text it would not format correctly):

Screenshot 2023-03-08 at 15 21 45

But when downloaded the file won't open. When it comes to size the decrypted file that I download is larger then the one I upload. So I am not sure if it's encryption or decryption that corrupts it, or something else.

When I try with a plain .txt and log the encryptedData.toString() I get again a long string of random characters and when I log decryptedData then it logs the content of the .txt file, but when I download it as text/plain it's just empty. So plan txt doesn't work either.

khbeieb commented 1 year ago

@nalnir

did you find any solution ?