From 2905748836d167bd0300ea286bed47fce903b094 Mon Sep 17 00:00:00 2001 From: nf404 Date: Sun, 7 Jul 2019 22:26:43 +0200 Subject: [PATCH] Optimize padding calculation --- src/hasher/hasher.mjs | 3 +++ src/hasher/hasher32be.mjs | 11 ++++++----- src/hasher/hasher32le.mjs | 12 +++++++----- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/hasher/hasher.mjs b/src/hasher/hasher.mjs index abead03..dcd5b11 100644 --- a/src/hasher/hasher.mjs +++ b/src/hasher/hasher.mjs @@ -118,6 +118,7 @@ class Hasher { /** * Add PKCS7 padding to message + * Pad with bytes all of the same value as the number of padding bytes * * @protected * @param {number} length @@ -128,6 +129,7 @@ class Hasher { /** * Add ISO7816-4 padding to message + * Pad with 0x80 followed by zero bytes * * @protected * @param {number} length @@ -138,6 +140,7 @@ class Hasher { /** * Add zero padding to message + * Pad with 0x00 characters * * @protected * @param {number} length diff --git a/src/hasher/hasher32be.mjs b/src/hasher/hasher32be.mjs index 0d8ae61..f2add88 100644 --- a/src/hasher/hasher32be.mjs +++ b/src/hasher/hasher32be.mjs @@ -81,11 +81,12 @@ class Hasher32be extends Hasher { */ addLengthBits() { // @todo fix length to 64 bit - this.state.message += "\x00\x00\x00\x00"; - let lengthBits = this.state.length << 3; - for (let i = 3; i >= 0; i--) { - this.state.message += String.fromCharCode(lengthBits >> (i << 3)); - } + this.state.message += "\x00\x00\x00" + + String.fromCharCode(this.state.length >> 29 & 0xff) + + String.fromCharCode(this.state.length >> 21 & 0xff) + + String.fromCharCode(this.state.length >> 13 & 0xff) + + String.fromCharCode(this.state.length >> 5 & 0xff) + + String.fromCharCode(this.state.length << 3 & 0xff); } } diff --git a/src/hasher/hasher32le.mjs b/src/hasher/hasher32le.mjs index dccbc88..3208905 100644 --- a/src/hasher/hasher32le.mjs +++ b/src/hasher/hasher32le.mjs @@ -75,12 +75,14 @@ class Hasher32le extends Hasher { * @protected */ addLengthBits() { - let lengthBits = this.state.length << 3; - for (let i = 0; i < 4; i++) { - this.state.message += String.fromCharCode(lengthBits >> (i << 3)); - } // @todo fix length to 64 bit - this.state.message += "\x00\x00\x00\x00"; + this.state.message += + String.fromCharCode(this.state.length << 3 & 0xff) + + String.fromCharCode(this.state.length >> 5 & 0xff) + + String.fromCharCode(this.state.length >> 13 & 0xff) + + String.fromCharCode(this.state.length >> 21 & 0xff) + + String.fromCharCode(this.state.length >> 29 & 0xff) + + "\x00\x00\x00"; } }