I have a simple web application for uploading zip files to a server. In the Javascript part I have used a try-catch block for checking whether the files are password protected(A predefined and known password) by reading the entries and catching the corresponding error.
The js library which I am using is https://github.com/gildas-lormeau/zip.js/blob/master/dist/zip.min.js.
let reader;
try {
reader = new zip.ZipReader(new zip.BlobReader(file), {
password
});
const entries = await reader.getEntries();
for (const entry of entries) {
try {
await entry.getData(new zip.BlobWriter(), {
onprogress: (index, max) => {
zip.BlobWriter.$cancel()
reader.close()
}
});
} catch (error) {
if (error.message === zip.ERR_ENCRYPTED ||
error.message === zip.ERR_INVALID_PASSWORD) {
alert("Incorrect password")
return false;
} else {
console.log(error)
}
}
}
} catch (error) {
console.log(error)
} finally {
await reader.close();
}
The above code successfully finds out if the file is not encrypted by the predetermined password. However, for some files the error statement is as below. TypeError: Cannot read properties of undefined (reading 'importKey')
I would like to know why this happens and how to know whether the file is password protected or not.
Thank You
There are some issues with the code you proposed, for example BlobWriter.$cancel is not documented anywhere and does not exist actually. Also, you should call reader.close() only once.
Here is below how such a function could be written.
const verifyZipPassword = async (file, password) => {
const reader = new zip.ZipReader(new zip.BlobReader(file), { password });
const entries = await reader.getEntries();
try {
for (const entry of entries) {
const abortController = new AbortController();
const signal = abortController.signal;
const onprogress = () => abortController.abort();
await entry.getData(new zip.BlobWriter(), { signal, onprogress });
}
} catch (error) {
if (error.message == zip.ERR_INVALID_PASSWORD) {
return false;
} else if (error.message != zip.ERR_ABORT) {
throw error;
}
} finally {
await reader.close();
}
return true;
};