How to determine if PDF is encrypted javascript client side

Viewed 2741

Need to determine if if pdf uploaded by user is password protected without using external libs. So far got this POC.

Any one know cases when this might not work?

<input type='file' onchange='openFile(event)'><br>
<script>
    var openFile = function (event) {

        var input = event.target;

        var reader = new FileReader();
        reader.onload = function (event) {
            console.clear();
            var contents = event.target.result;
            if (contents.indexOf('/Encrypt') !== -1) {
                console.log("Is encrypted");
            } else {
                console.log("Not encrypted");
            }
            console.log("File contents: " + contents);
        };

        reader.onerror = function (event) {
            console.error("File could not be read! Code "  +event.target.error.code);
        };

        reader.readAsText(input.files[0]);

    };
</script>
1 Answers

You can use the below code to find whether the PDF is encrypted or not

const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function () {

var files = new Blob([reader.result], {type: 'application/pdf'});
files.text().then(x=> {
    console.log("isEncrypted", x.includes("Encrypt"))
    console.log("isEncrypted", x.substring(x.lastIndexOf("<<"), x.lastIndexOf(">>")).includes("/Encrypt"));
    console.log(file.name);
});
Related