UNPKG

@stellot/crypto

Version:

Crypto libraries for front and backend

27 lines (26 loc) 1 kB
import { eddsa as Eddsa } from 'elliptic'; import { sha256 } from 'js-sha256'; import { sha512 } from 'js-sha512'; import { encrypt as _encrypt, decrypt as _decrypt } from '@stellot/secret-box'; export function encrypt(privKey, pubKey, input, nonce, authenticate = true) { const key = deriveKey(privKey, pubKey); return _encrypt(input, key, nonce, authenticate); } export function decrypt(privKey, pubKey, input, nonce, authenticate = true) { const key = deriveKey(privKey, pubKey); return _decrypt(input, key, nonce, authenticate); } const ec = new Eddsa('ed25519'); function deriveKey(privKey, pubKey) { const scalar = ec.decodeInt(getScalar(privKey)); const point = ec.decodePoint(pubKey.toString('hex')); const secret = ec.encodePoint(point.mul(scalar)); return Buffer.from(sha256.arrayBuffer(secret)); } function getScalar(seed) { const hash = sha512.array(seed); hash[0] &= 0xf8; hash[31] &= 0x3f; hash[31] |= 0x40; return hash.slice(0, 32); }