Skip to content

Commit

Permalink
Heap & asm pooling
Browse files Browse the repository at this point in the history
  • Loading branch information
twiss committed Jun 29, 2018
1 parent 9dcaf4c commit aa21f46
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions src/aes/aes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,40 @@ import { AES_asm } from './aes.asm';
import { _heap_init, _heap_write, is_bytes, is_number } from '../utils';
import { IllegalArgumentError, SecurityError } from '../errors';

const heap_pool = [];
const asm_pool = [];

export class AES {
constructor(key, iv, padding, heap, asm) {
this.nonce = null;
this.counter = 0;
this.counterSize = 0;

this.heap = _heap_init(Uint8Array, heap).subarray(AES_asm.HEAP_DATA);
this.asm = asm || AES_asm(null, this.heap.buffer);
this.mode = null;
this.key = null;

this.AES_reset(key, iv, padding);
this.key = key;
this.iv = iv;
this.padding = padding;

this.acquireResources(heap, asm);
}

acquireResources(heap, asm) {
if (!this.heap && !this.asm) {
console.log(heap, heap_pool.slice(-1));
this.heap = _heap_init(Uint8Array, heap || heap_pool.pop()).subarray(AES_asm.HEAP_DATA);
this.asm = asm || asm_pool.pop() || AES_asm(null, this.heap.buffer);
this.AES_reset(this.key, this.iv, this.padding);
}
}

releaseResources() {
if (this.heap.buffer.byteLength !== 0x100000) { // shared asm.js heap
heap_pool.push(new Uint8Array(this.heap.buffer));
asm_pool.push(this.asm);
this.heap = undefined;
this.asm = undefined;
}
}

/**
Expand Down Expand Up @@ -114,7 +136,7 @@ export class AES {
this.iv = iv;
this.asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
} else {
this.iv = null;
this.iv = undefined;
this.asm.set_iv(0, 0, 0, 0);
}
}
Expand Down Expand Up @@ -198,6 +220,8 @@ export class AES {
* @param {Uint8Array} data
*/
AES_Encrypt_finish(data) {
this.acquireResources();

var presult = null,
prlen = 0;

Expand Down Expand Up @@ -239,6 +263,8 @@ export class AES {
this.pos = 0;
this.len = 0;

this.releaseResources();

return this;
}

Expand Down Expand Up @@ -299,6 +325,8 @@ export class AES {
* @param {Uint8Array} data
*/
AES_Decrypt_finish(data) {
this.acquireResources();

var presult = null,
prlen = 0;

Expand Down Expand Up @@ -352,6 +380,8 @@ export class AES {
this.pos = 0;
this.len = 0;

this.releaseResources();

return this;
}
}

0 comments on commit aa21f46

Please sign in to comment.