@crpdo/key
Version:
Streamlines key generation, derivation, and management through its simple and intuitive API
55 lines (48 loc) • 1.79 kB
JavaScript
const Nacl = require('@crpdo/crypto/nacl')
const BaseKey = require('./base-key')
/**
* Class representing a BoxKey.
* BoxKey is a key used for encryption and decryption.
* @extends BaseKey
*/
class BoxKey extends BaseKey {
/**
* Create a BoxKey.
* @param {string} seed - The seed used to create the BoxKey.
*/
constructor(seed) {
super(Nacl.createBoxKey(seed))
}
/**
* Encrypts data.
* @param {string} data - The data to be encrypted.
* @param {string} publicKey - The public key used for encryption. Defaults to the BoxKey's public key if not provided.
* @param {string} nonce - The nonce used for encryption.
* @param {boolean} encode - Flag to encode the result. If true, the result is base64 encoded.
* @returns {string} The encrypted data.
*/
encrypt(data, publicKey, nonce, encode) {
return Nacl.boxEncrypt(data, publicKey || this.publicKey, this.privateKey, nonce, encode)
}
/**
* Decrypts data.
* @param {string} data - The data to be decrypted.
* @param {string} publicKey - The public key used for decryption. Defaults to the BoxKey's public key if not provided.
* @param {string} nonce - The nonce used for decryption.
* @param {boolean} encode - Flag to decode the result. If true, the result is base64 decoded.
* @returns {string} The decrypted data.
*/
decrypt(data, publicKey, nonce, encode) {
return Nacl.boxDecrypt(data, publicKey || this.publicKey, this.privateKey, nonce, encode)
}
/**
* Converts a SignKey to a BoxKey.
* @param {KeyPair} keyPair - The SignKey to be converted.
* @returns {BoxKey} The converted BoxKey.
*/
static fromSignKey(keyPair) {
const key = Nacl.convertKeyPair(keyPair)
return new BoxKey(key.privateKey)
}
}
module.exports = BoxKey