@ufdevsllc/auth-me
Version:
Comprehensive licensing, security monitoring, and data mirroring package with hardcoded vendor-controlled database connection
1 lines • 2.5 kB
JavaScript
const crypto=require("crypto");class EncryptionManager{static get ALGORITHM(){return"aes-256-gcm"}static get KEY_LENGTH(){return 32}static get IV_LENGTH(){return 16}static get TAG_LENGTH(){return 16}static deriveKey(t,e="secure-guard-salt"){if(!t||"string"!=typeof t)throw new Error("Environment string is required for key derivation");const r=`${t}:${e}:${process.version}:${__dirname}`;return crypto.pbkdf2Sync(r,e,1e5,this.KEY_LENGTH,"sha256")}static generateIV(){return crypto.randomBytes(this.IV_LENGTH)}static encrypt(t,e,r=null){if(!t||"string"!=typeof t)throw new Error("Data must be a non-empty string");if(!Buffer.isBuffer(e)||e.length!==this.KEY_LENGTH)throw new Error(`Key must be a ${this.KEY_LENGTH}-byte Buffer`);if(r||(r=this.generateIV()),!Buffer.isBuffer(r)||r.length!==this.IV_LENGTH)throw new Error(`IV must be a ${this.IV_LENGTH}-byte Buffer`);try{const n=crypto.createCipheriv(this.ALGORITHM,e,r);n.setAAD(Buffer.from("secure-guard-aad"));let s=n.update(t,"utf8","base64");s+=n.final("base64");const i=n.getAuthTag();return{encrypted:s,iv:r.toString("base64"),tag:i.toString("base64")}}catch(t){throw new Error(`Encryption failed: ${t.message}`)}}static decrypt(t,e){if(!t||"object"!=typeof t)throw new Error("EncryptedData must be an object");const{encrypted:r,iv:n,tag:s}=t;if(!r||!n||!s)throw new Error("EncryptedData must contain encrypted, iv, and tag properties");if(!Buffer.isBuffer(e)||e.length!==this.KEY_LENGTH)throw new Error(`Key must be a ${this.KEY_LENGTH}-byte Buffer`);try{const t=Buffer.from(n,"base64"),i=Buffer.from(s,"base64"),a=crypto.createDecipheriv(this.ALGORITHM,e,t);a.setAAD(Buffer.from("secure-guard-aad")),a.setAuthTag(i);let o=a.update(r,"base64","utf8");return o+=a.final("utf8"),o}catch(t){throw new Error(`Decryption failed: ${t.message}`)}}static encryptRuntimeComponent(t,e){const r=this.deriveKey(e,"runtime-component-salt");return this.encrypt(t,r)}static decryptRuntimeComponent(t,e){const r=this.deriveKey(e,"runtime-component-salt");return this.decrypt(t,r)}static encryptConfig(t,e){const r=JSON.stringify(t),n=this.deriveKey(e,"config-salt");return this.encrypt(r,n)}static decryptConfig(t,e){const r=this.deriveKey(e,"config-salt"),n=this.decrypt(t,r);return JSON.parse(n)}static generateHash(t,e="sha256"){return crypto.createHash(e).update(t).digest("hex")}static verifyHash(t,e,r="sha256"){const n=this.generateHash(t,r);return crypto.timingSafeEqual(Buffer.from(n,"hex"),Buffer.from(e,"hex"))}}module.exports=EncryptionManager;