UNPKG

shh-client

Version:

The Shh.. protocol v0.0.1 Beta Tested. Keeps your messages very secure. Currently in more testing and securty.

65 lines (58 loc) 1.99 kB
import crypto from "crypto"; /** * Generate a private key or derive a public key * @param {'private'|'public'} type * @param {Buffer} [privKey] - Only needed if type === 'public' */ export function generateKey(type, name) { if (type === "private") { // Return private key buffer const ecdh = crypto.createECDH('prime256v1'); ecdh.generateKeys(); return ecdh.getPrivateKey(); } else { throw new Error(`Use derivePublicKey() to get public key from private key`); } } /** * Derives a public key from a given private key */ export function derivePublicKey(privKey) { const ecdh = crypto.createECDH('prime256v1'); ecdh.setPrivateKey(privKey); return ecdh.getPublicKey(); } /** * Generate a shared key using own private key and peer's public key */ export function generateSharedKey(privKey, peerPubKey) { const ecdh = crypto.createECDH('prime256v1'); ecdh.setPrivateKey(privKey); return ecdh.computeSecret(peerPubKey); } /** * Simple encrypt/decrypt functions (AES-256-GCM) */ export function enc(obj, sharedKey) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', sharedKey.slice(0, 32), iv); let encrypted = cipher.update(JSON.stringify(obj), 'utf8', 'hex'); encrypted += cipher.final('hex'); const tag = cipher.getAuthTag(); return { iv: iv.toString('hex'), tag: tag.toString('hex'), data: encrypted }; } export function dec(encData, sharedKey) { const iv = Buffer.from(encData.iv, 'hex'); const tag = Buffer.from(encData.tag, 'hex'); const decipher = crypto.createDecipheriv('aes-256-gcm', sharedKey.slice(0, 32), iv); decipher.setAuthTag(tag); let decrypted = decipher.update(encData.data, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return JSON.parse(decrypted); } /** * Example sending function (stub) */ export function toServer(url, payload) { console.log(`Sending to ${url}:`, payload); }