Skip to content

Commit

Permalink
reduce buffer creation for ctr mode
Browse files Browse the repository at this point in the history
  • Loading branch information
dignifiedquire authored and dcousens committed Aug 18, 2017
1 parent 94007f4 commit 040d953
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
8 changes: 6 additions & 2 deletions aes.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,13 @@ AES.prototype._reset = function () {
this._invKeySchedule = invKeySchedule
}

AES.prototype.encryptBlock = function (M) {
AES.prototype.encryptBlockRaw = function (M) {
M = asUInt32Array(M)
var out = cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
}

AES.prototype.encryptBlock = function (M) {
var out = this.encryptBlockRaw(M)
var buf = Buffer.allocUnsafe(16)
buf.writeUInt32BE(out[0], 0)
buf.writeUInt32BE(out[1], 4)
Expand Down
2 changes: 1 addition & 1 deletion bench/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ let key = Buffer.alloc(16, 0xff)
let iv = Buffer.alloc(16, 0x01)

function test (mod, message) {
let cipher = mod.createCipheriv('aes-128-cbc', key, iv)
let cipher = mod.createCipheriv('aes-128-ctr', key, iv)
let b = cipher.update(message)
return Buffer.concat([b, cipher.final()])
}
Expand Down
18 changes: 15 additions & 3 deletions modes/ctr.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,26 @@ function incr32 (iv) {
}

function getBlock (self) {
var out = self._cipher.encryptBlock(self._prev)
var out = self._cipher.encryptBlockRaw(self._prev)
incr32(self._prev)
return out
}

var blockSize = 16
exports.encrypt = function (self, chunk) {
while (self._cache.length < chunk.length) {
self._cache = Buffer.concat([self._cache, getBlock(self)])
var chunkNum = Math.ceil(chunk.length / blockSize)
var start = self._cache.length
self._cache = Buffer.concat([
self._cache,
Buffer.allocUnsafe(chunkNum * blockSize)
])
for (var i = 0; i < chunkNum; i++) {
var out = getBlock(self)
var offset = start + i * blockSize
self._cache.writeUInt32BE(out[0], offset + 0)
self._cache.writeUInt32BE(out[1], offset + 4)
self._cache.writeUInt32BE(out[2], offset + 8)
self._cache.writeUInt32BE(out[3], offset + 12)
}
var pad = self._cache.slice(0, chunk.length)
self._cache = self._cache.slice(chunk.length)
Expand Down

0 comments on commit 040d953

Please sign in to comment.