I am working on a application where I am selecting pdf file from local file and encrypting it with openpgpjs. Though I am able to encrypt the pdf, When I try to open the encrypted pdf in chrome it is showing dialog with message "Failed to load PDF document.".
But when I decrypt the file manually it is showing original pdf properly.
Here is the code snippet:
Select file and assign to uint8Array
:
//file picker listener uint8Array
document.getElementById("file_picker").onchange = function (event) {
var file = event.target.files[0];
console.log(file);
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.addEventListener('load', (loadEvent) => {
console.log("array data")
var buffer = loadEvent.target.result;
uint8Array = new Uint8Array(buffer);
console.log(uint8Array);
})
}
Encrypt and download encrypted file :
//encrypt click listener
document
.getElementById("encrypt")
.addEventListener("click", function (e) {
//
if (uint8Array != undefined) {
(async () => {
const message = await openpgp.createMessage({ binary: uint8Array });
const encrypted = await openpgp.encrypt({
message, // input as Message object
passwords: ['password'], // multiple passwords possible
format: 'binary' // don't ASCII armor (for Uint8Array output)
});
console.log(encrypted); // Uint8Array
downloadBlob(encrypted, 'data.pdf', 'application/pdf');
})();
}
//
});
function downloadBlob(data, fileName, mimeType) {
var blob, url;
blob = new Blob([data], {
type: mimeType
});
url = window.URL.createObjectURL(blob);
downloadURL(url, fileName);
setTimeout(function () {
return window.URL.revokeObjectURL(url);
}, 1000);
}
function downloadURL(data, fileName) {
var a;
a = document.createElement('a');
a.href = data;
a.download = fileName;
document.body.appendChild(a);
a.style = 'display: none';
a.click();
a.remove();
}
I can see the pdf getting download but when I open it, It is showing dialog with message saying "Failed to load PDF document.".
Do I need to set any value to get dialog popup?
Updated:
FYI: I have tried with CryptoJs with AES encryption from here and I still get the same issue.
Expected output should show prompt dialog like below: