UNPKG

@ixo/supamoto-bot-sdk

Version:

An SDK to easily interact with Supamoto bot db

39 lines (37 loc) 1.38 kB
import crypto from 'crypto'; export function hkdfSha256(ikm, info, length = 32) { return Buffer.from(crypto.hkdfSync('sha256', ikm, /*salt*/Buffer.alloc(0), Buffer.from(info, 'utf8'), length)); } export function aadFor(parts, table, v = 1) { // canonical: table|v|part1|part2|... const s = [table, String(v), ...parts.map(String)].join('|'); return Buffer.from(s, 'utf8'); } // AEAD encrypt/decrypt (AES-256-GCM) export function encryptData({ data, aad }, key) { const nonce = crypto.randomBytes(12); // 96-bit nonce const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce); if (aad) cipher.setAAD(aad); const ct = Buffer.concat([cipher.update(data), cipher.final()]); const tag = cipher.getAuthTag(); // Envelope: 1B version | 12B nonce | 16B tag | ciphertext return Buffer.concat([Buffer.from([1]), nonce, tag, ct]); } export function decryptData({ data, aad }, key) { if (data.length < 1 + 12 + 16) throw new Error('ciphertext too short'); const ver = data.readUInt8(0); if (ver !== 1) throw new Error('unsupported version'); const nonce = data.subarray(1, 13); const tag = data.subarray(13, 29); const ct = data.subarray(29); const decipher = crypto.createDecipheriv('aes-256-gcm', key, nonce); if (aad) decipher.setAAD(aad); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(ct), decipher.final()]); }