Skip to content

Commit 040d953

Browse files
dignifiedquiredcousens
authored andcommitted
reduce buffer creation for ctr mode
1 parent 94007f4 commit 040d953

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

aes.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -187,9 +187,13 @@ AES.prototype._reset = function () {
187187
this._invKeySchedule = invKeySchedule
188188
}
189189

190-
AES.prototype.encryptBlock = function (M) {
190+
AES.prototype.encryptBlockRaw = function (M) {
191191
M = asUInt32Array(M)
192-
var out = cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
192+
return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
193+
}
194+
195+
AES.prototype.encryptBlock = function (M) {
196+
var out = this.encryptBlockRaw(M)
193197
var buf = Buffer.allocUnsafe(16)
194198
buf.writeUInt32BE(out[0], 0)
195199
buf.writeUInt32BE(out[1], 4)

bench/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ let key = Buffer.alloc(16, 0xff)
55
let iv = Buffer.alloc(16, 0x01)
66

77
function test (mod, message) {
8-
let cipher = mod.createCipheriv('aes-128-cbc', key, iv)
8+
let cipher = mod.createCipheriv('aes-128-ctr', key, iv)
99
let b = cipher.update(message)
1010
return Buffer.concat([b, cipher.final()])
1111
}

modes/ctr.js

+15-3
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,26 @@ function incr32 (iv) {
1616
}
1717

1818
function getBlock (self) {
19-
var out = self._cipher.encryptBlock(self._prev)
19+
var out = self._cipher.encryptBlockRaw(self._prev)
2020
incr32(self._prev)
2121
return out
2222
}
2323

24+
var blockSize = 16
2425
exports.encrypt = function (self, chunk) {
25-
while (self._cache.length < chunk.length) {
26-
self._cache = Buffer.concat([self._cache, getBlock(self)])
26+
var chunkNum = Math.ceil(chunk.length / blockSize)
27+
var start = self._cache.length
28+
self._cache = Buffer.concat([
29+
self._cache,
30+
Buffer.allocUnsafe(chunkNum * blockSize)
31+
])
32+
for (var i = 0; i < chunkNum; i++) {
33+
var out = getBlock(self)
34+
var offset = start + i * blockSize
35+
self._cache.writeUInt32BE(out[0], offset + 0)
36+
self._cache.writeUInt32BE(out[1], offset + 4)
37+
self._cache.writeUInt32BE(out[2], offset + 8)
38+
self._cache.writeUInt32BE(out[3], offset + 12)
2739
}
2840
var pad = self._cache.slice(0, chunk.length)
2941
self._cache = self._cache.slice(chunk.length)

0 commit comments

Comments
 (0)