UNPKG

nubli

Version:
77 lines (76 loc) 2.72 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const libsodium_wrappers_1 = __importDefault(require("libsodium-wrappers")); const array_buffer_to_hex_1 = __importDefault(require("array-buffer-to-hex")); const hsalsa20_1 = require("./hsalsa20"); class Credentials { constructor(publicKey, privateKey, slPublicKey, sharedSecret) { this._slPublicKey = null; this._sharedSecret = null; if (publicKey == null || privateKey == null) { let key = this.generateKeyPair(); publicKey = key.publicKey; privateKey = key.privateKey; } if (slPublicKey != null) { this._slPublicKey = slPublicKey; } if (sharedSecret != null) { this._sharedSecret = sharedSecret; } this._publicKey = publicKey; this._privateKey = privateKey; } generateKeyPair() { let key = libsodium_wrappers_1.default.crypto_box_keypair(); if (key.keyType != "x25519") { throw new Error("Key has an unexpected type"); } return key; } generateDHKey() { return libsodium_wrappers_1.default.crypto_scalarmult(this._privateKey, this.slPublicKey); } generateSharedKey() { let dhKey = this.generateDHKey(); let sharedSecret = new Buffer(32); let inv = new Buffer(16); inv.fill(0); let crypto = new Buffer("expand 32-byte k"); hsalsa20_1.Hsalsa20.crypto_core(sharedSecret, inv, dhKey, crypto); this._sharedSecret = sharedSecret; } serialize() { return { slPublicKey: this._slPublicKey ? this._slPublicKey.toString('hex') : "", publicKey: array_buffer_to_hex_1.default(this._publicKey), privateKey: array_buffer_to_hex_1.default(this._privateKey), sharedSecret: this._sharedSecret ? this._sharedSecret.toString('hex') : "", }; } get slPublicKey() { if (!this._slPublicKey) { throw new Error("Smart Lock public key is missing."); } return this._slPublicKey; } set slPublicKey(publicKey) { if (this._slPublicKey) { throw new Error("Cannot override an already set Smart Lock public key."); } this._slPublicKey = publicKey; } get publicKey() { return this._publicKey; } get sharedSecret() { if (!this._sharedSecret) { this.generateSharedKey(); } return this._sharedSecret; } } exports.Credentials = Credentials;