UNPKG

ashcrypt

Version:
2 lines (1 loc) 2.44 kB
import{createReadStream as g,createWriteStream as p}from"fs";import"stream";import T from"parallel-transform";var m=class{algorithm;parallel=1;constructor({algorithm:r,maxParallel:t}){this.algorithm=r,t&&(this.parallel=t)}create(r){let t=this.algorithm,e=t.chunkSize,i=t.getChunkSize(e),[s,n]=r==="encrypt"?[e,i]:[i,e],a=0;return T(this.parallel,{ordered:!0,writableHighWaterMark:s,readableHighWaterMark:n},(y,c)=>{console.log("chunk: ",a),a++,t[r](y).then(h=>c(null,h)).catch(h=>c(h))})}read(r,t){let e=this.algorithm.getChunkSize(this.algorithm.chunkSize),i=this.create(t);return g(r,{highWaterMark:t==="decrypt"?e:this.algorithm.chunkSize}).pipe(i)}write(r){return p(r)}};import{createCipheriv as d,createDecipheriv as S,pbkdf2 as A,randomBytes as l}from"crypto";var o=class{name;chunkSize;constructor({name:r,chunkSize:t}){this.name=r,this.chunkSize=t}};var f=class extends o{IV_LENGTH=12;TAG_LENGTH=16;SALT_LENGTH;TAG_POSITION;ENCRYPTED_POSITION;KEYLEN;HASH;algorithm;secret;iterations;constructor({secret:r,chunkSize:t=512*1e3,algorithm:e="aes-256-gcm",iterations:i=1e5}){super({name:e,chunkSize:t}),this.algorithm=e,this.secret=r,this.iterations=i,this.SALT_LENGTH=this.algorithm.includes("128")||this.algorithm.includes("192")?16:32,this.KEYLEN=this.algorithm.includes("128")?16:this.algorithm.includes("192")?24:32,this.HASH=this.algorithm.includes("128")?"sha256":this.algorithm.includes("192")?"sha384":"sha512",this.TAG_POSITION=this.SALT_LENGTH+this.IV_LENGTH,this.ENCRYPTED_POSITION=this.TAG_POSITION+this.TAG_LENGTH}getKey(r){return new Promise((t,e)=>A(this.secret,r,this.iterations,this.KEYLEN,this.HASH,(i,s)=>{if(i)return e(i);t(s)}))}getChunkSize(r){return r+this.ENCRYPTED_POSITION}async encrypt(r){let t=l(this.IV_LENGTH),e=l(this.SALT_LENGTH),i=await this.getKey(e);if(i instanceof Error)throw i;let s=d(this.algorithm,i,t),n=Buffer.concat([s.update(r),s.final()]),a=s.getAuthTag();return Buffer.concat([e,t,a,n])}async decrypt(r){if(r.length<this.ENCRYPTED_POSITION)throw new Error("Invalid ciphertext buffer");console.log(r.toBase64());let t=r.subarray(0,this.SALT_LENGTH),e=r.subarray(this.SALT_LENGTH,this.TAG_POSITION),i=r.subarray(this.TAG_POSITION,this.ENCRYPTED_POSITION),s=r.subarray(this.ENCRYPTED_POSITION),n=await this.getKey(t);if(n instanceof Error)throw n;let a=S(this.algorithm,n,e);return a.setAuthTag(i),Buffer.concat([a.update(s),a.final()])}};export{f as AES,o as BaseAlgorithm,m as Stream};