UNPKG

@hackbg/miscreant-esm

Version:

(ESM port) Misuse resistant symmetric encryption library providing AES-SIV (RFC 5297), AES-PMAC-SIV, and STREAM constructions

44 lines (43 loc) 1.17 kB
import Block from "../../internals/block.dist.mjs"; export default class SoftAesCtr { _counter; _buffer; _cipher; constructor(cipher) { this._cipher = cipher; this._counter = new Block(); this._buffer = new Block(); } clear() { this._buffer.clear(); this._counter.clear(); this._cipher.clear(); return this; } async encryptCtr(iv, plaintext) { if (iv.length !== Block.SIZE) { throw new Error("CTR: iv length must be equal to cipher block size"); } this._counter.data.set(iv); let bufferPos = Block.SIZE; const result = new Uint8Array(plaintext.length); for (let i = 0; i < plaintext.length; i++) { if (bufferPos === Block.SIZE) { this._buffer.copy(this._counter); this._cipher.encryptBlock(this._buffer); bufferPos = 0; incrementCounter(this._counter); } result[i] = plaintext[i] ^ this._buffer.data[bufferPos++]; } return result; } } function incrementCounter(counter) { let carry = 1; for (let i = Block.SIZE - 1; i >= 0; i--) { carry += counter.data[i] & 0xff | 0; counter.data[i] = carry & 0xff; carry >>>= 8; } }