UNPKG

@averox/cryptosphare

Version:

Real-time SDK for end-to-end encrypted messaging, key monitoring, and secure A/V streaming

70 lines (69 loc) 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Encryption = void 0; const elliptic_1 = require("elliptic"); const crypto_1 = require("crypto"); class Encryption { constructor() { this.SALT_LENGTH = 32; this.IV_LENGTH = 12; this.ec = new elliptic_1.ec('secp256k1'); } deriveKey(password, salt) { return (0, crypto_1.createHash)('sha256') .update(Buffer.concat([Buffer.from(password), salt])) .digest(); } encryptData(data, key) { const salt = (0, crypto_1.randomBytes)(this.SALT_LENGTH); const iv = (0, crypto_1.randomBytes)(this.IV_LENGTH); const derivedKey = this.deriveKey(key, salt); const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', derivedKey, iv); const encrypted = Buffer.concat([cipher.update(Buffer.from(data, 'utf8')), cipher.final()]); return { encrypted: encrypted.toString('base64'), iv: iv.toString('base64'), salt: salt.toString('base64'), tag: cipher.getAuthTag().toString('base64'), }; } decryptData(encryptedData, key) { const salt = Buffer.from(encryptedData.salt, 'base64'); const iv = Buffer.from(encryptedData.iv, 'base64'); const tag = Buffer.from(encryptedData.tag, 'base64'); const derivedKey = this.deriveKey(key, salt); const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', derivedKey, iv); decipher.setAuthTag(tag); const decrypted = Buffer.concat([ decipher.update(Buffer.from(encryptedData.encrypted, 'base64')), decipher.final(), ]); return decrypted.toString('utf8'); } generateECDSAKeyPair() { const keyPair = this.ec.genKeyPair(); return { publicKey: keyPair.getPublic('hex'), privateKey: keyPair.getPrivate('hex'), }; } signData(data, privateKey) { const key = this.ec.keyFromPrivate(privateKey, 'hex'); const hash = (0, crypto_1.createHash)('sha256').update(data).digest('hex'); const signature = key.sign(hash, { canonical: true }); return signature.toDER('hex'); } verifySignature(data, signature, publicKey) { const key = this.ec.keyFromPublic(publicKey, 'hex'); const hash = (0, crypto_1.createHash)('sha256').update(data).digest('hex'); return key.verify(hash, signature); } quantumResistantEncrypt(data, publicKey) { const ephemeralKeyPair = this.generateECDSAKeyPair(); const sharedSecret = this.ec .keyFromPrivate(ephemeralKeyPair.privateKey, 'hex') .derive(this.ec.keyFromPublic(publicKey, 'hex').getPublic()); return this.encryptData(data, sharedSecret.toString('hex')).encrypted; } } exports.Encryption = Encryption;