Skip to content

Commit

Permalink
Use subarray() instead of slice()
Browse files Browse the repository at this point in the history
This significantly reduces memory usage and time it takes to run
verifyPackage(). On my machine it went down from ~1000ms to ~700ms on
average.
  • Loading branch information
luk1337 committed Dec 26, 2023
1 parent 79fbdaa commit c17421d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/components/verify-tab/VerifyTabPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export default {
verifyFile(blob) {
const fileReader = new FileReader();
fileReader.onload = async () => {
const result = await CryptoService.verifyPackage(fileReader.result);
const result = await CryptoService.verifyPackage(new Uint8Array(fileReader.result));
this.fileName = blob.name;
this.isVerified = result.status;
this.verifyResult = result.msg;
Expand Down
16 changes: 10 additions & 6 deletions src/js/CryptoService.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import forge from 'node-forge';

export default class CryptoService {
static arrayBufferToString(data) {
return String.fromCharCode.apply(null, new Uint8Array(data));
return this.u8ArrayToString(new Uint8Array(data));
}

static u8ArrayToString(data) {
return String.fromCharCode.apply(null, data);
}

static async verifyPackage(data) {
const footer = new Uint8Array(data.slice(-6));
const footer = data.subarray(-6);
const commentSize = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8);
const signatureStart = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8);

Expand All @@ -19,7 +23,7 @@ export default class CryptoService {

// Check that we have found the start of the
// end-of-central-directory record.
const eocd = new Uint8Array(data.slice(-(commentSize + 22), data.byteLength));
const eocd = data.subarray(-(commentSize + 22), data.byteLength);

if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) {
return {
Expand All @@ -37,8 +41,8 @@ export default class CryptoService {
}
}

const signature = data.slice(-signatureStart, data.byteLength - footer.length);
const asn = forge.asn1.fromDer(this.arrayBufferToString(signature));
const signature = data.subarray(-signatureStart, data.byteLength - footer.length);
const asn = forge.asn1.fromDer(this.u8ArrayToString(signature));
const pkcs = forge.pkcs7.messageFromAsn1(asn);
const certificate = pkcs.certificates[0];

Expand All @@ -62,7 +66,7 @@ export default class CryptoService {
validity: certificate.validity,
};

const message = data.slice(0, data.byteLength - commentSize - 2);
const message = data.subarray(0, data.byteLength - commentSize - 2);
let messageDigest = undefined;

switch (certificate.siginfo.algorithmOid) {
Expand Down

0 comments on commit c17421d

Please sign in to comment.