@crpdo/key
Version:
Streamlines key generation, derivation, and management through its simple and intuitive API
50 lines (43 loc) • 1.48 kB
JavaScript
const Nacl = require('@crpdo/crypto/nacl')
const BaseKey = require('./base-key')
/**
* This class extends BaseKey and provides methods for signing and verifying messages
* using the Nacl library. The messages are signed using the privateKey property of
* the SignKey instance, and they can be verified using a given publicKey or the
* publicKey property of the SignKey instance.
*/
class SignKey extends BaseKey {
/**
* @param {string} seed - A seed string used to create the SignKey
*/
constructor(seed) {
super(Nacl.createSignKey(seed))
}
/**
* @param {string} data - The data to sign
* @returns {string} - The signed data
*/
sign(data) {
return Nacl.sign(data, this.key.privateKey)
}
/**
* @param {string} data - The data to verify
* @param {string} signature - The signature to check the data against
* @param {string} [publicKey] - The public key to use for verification.
* If not provided, the publicKey of the SignKey instance is used.
* @returns {boolean} - Returns true if the signature is valid, false otherwise
*/
verify(data, signature, publicKey) {
return Nacl.verify(data, signature, publicKey || this.key.publicKey)
}
/**
* Generates a SignKey from a given HDKey
* @param {object} hd - An HDKey instance
* @returns {SignKey} - A new SignKey instance
*/
static fromHdKey(hd) {
const seed = hd.privateExtendedKey
return new SignKey(seed)
}
}
module.exports = SignKey