UNPKG

gnablib

Version:

A lean, zero dependency library to provide a useful base for your project.

2 lines 1.15 kB
/*! Copyright 2023-2024 the gnablib contributors MPL-1.1 */ import{LengthError as t}from"../../error/LengthError.js";export class Cbc{constructor(r,e,c){if(c.length!=r.blockSize)throw new t(r.blockSize,"iv.length",c.length);this._crypt=r,this._pad=e,this._iv=c}get blockSize(){return this._crypt.blockSize}decryptInto(t,r){const e=this._crypt.blockSize,c=r.length-e;let s=0,i=0;t.set(r.subarray(0,c));let o=this._iv;for(;s<c;){const c=i*e;this._crypt.decryptBlock(t,i++);for(let r=0;r<e;r++)t[c+r]^=o[r];o=r.subarray(c,c+e),s+=e}const n=new Uint8Array(r.subarray(c));this._crypt.decryptBlock(n);for(let t=0;t<e;t++)n[t]^=o[t];t.set(this._pad.unpad(n),c)}encryptInto(t,r){const e=this._crypt.blockSize,c=r.length%e,s=r.length-c,i=s+(this._pad.padSize(0===c?e:c,e)>0?e:0);t.set(r.subarray(0,s));let o=0,n=0,p=this._iv;for(;o<s;){const r=n*e;for(let c=0;c<e;c++)t[r+c]^=p[c];this._crypt.encryptBlock(t,n++),p=t.subarray(r,r+e),o+=e}if(i>s){const c=this._pad.pad(r.subarray(s),e);t.set(c,o);for(let r=0;r<e;r++)t[o+r]^=p[r];this._crypt.encryptBlock(t,n)}}encryptSize(t){const r=this._crypt.blockSize,e=t%r;return this._pad.padSize(0===e?r:e,r)-e+t}}