From c0e165bf97aadbb562ad6acfd6f7a37f47a204a9 Mon Sep 17 00:00:00 2001 From: Calixte Denizet Date: Fri, 7 Oct 2022 14:38:39 +0200 Subject: [PATCH] Simplify the way to compute the remainder modulo 3 in PDF20Hash function I noticed the 256 % 3 (which is equal to 1) so I slighty simplify the code. The sum of the 16 Uint8 doesn't exceed 2^12, hence we can just take the sum modulo 3. --- src/core/crypto.js | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/core/crypto.js b/src/core/crypto.js index 4cce979cf28a2..22bf8aac11807 100644 --- a/src/core/crypto.js +++ b/src/core/crypto.js @@ -1304,15 +1304,11 @@ const PDF20 = (function PDF20Closure() { e = cipher.encrypt(k1, k.subarray(16, 32)); // Now we have to take the first 16 bytes of an unsigned big endian // integer and compute the remainder modulo 3. That is a fairly large - // number and JavaScript isn't going to handle that well, so we're using - // a trick that allows us to perform modulo math byte by byte. - let remainder = 0; - for (let z = 0; z < 16; z++) { - remainder *= 256 % 3; - remainder %= 3; - remainder += (e[z] >>> 0) % 3; - remainder %= 3; - } + // number and JavaScript isn't going to handle that well. + // The number is e0 + 256 * e1 + 256^2 * e2... and 256 % 3 === 1, hence + // the powers of 256 are === 1 modulo 3 and finally the number modulo 3 + // is equal to the remainder modulo 3 of the sum of the e_n. + const remainder = e.slice(0, 16).reduce((a, b) => a + b, 0) % 3; if (remainder === 0) { k = calculateSHA256(e, 0, e.length); } else if (remainder === 1) {