Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const sodium = require('libsodium-wrappers-sumo');
const extcrypto = require('../../extcrypto');
const V1 = require('../protocol/V1');
const V2 = require('../protocol/V2');
const utils = require('../utils');
const PublicKey = require('./public');
// patch
sodium.crypto_sign_KEYPAIRBYTES = sodium.crypto_sign_SECRETKEYBYTES + sodium.crypto_sign_PUBLICKEYBYTES;
/***
* PrivateKey
*
* private key for asymmetric cryptography
*
* @constructor
*
* @api public
*
* @param {Object} protocol
*/
module.exports = PrivateKey;
function PrivateKey(protocol) {
const self = this;
return sodium.ready.then(() => {
if (self.protocol() instanceof V2) {
if (!(rkey instanceof Buffer)) { return done(new TypeError('Raw key must be provided as a buffer')); }
const len = Buffer.byteLength(rkey);
if (len === sodium.crypto_sign_KEYPAIRBYTES) {
rkey = rkey.slice(0, sodium.crypto_sign_SECRETKEYBYTES);
} else if (len !== sodium.crypto_sign_SECRETKEYBYTES) {
if (len !== sodium.crypto_sign_SEEDBYTES) {
throw new Error('Secret keys must be 32 or 64 bytes long; ' + len + ' given.')
}
rkey = Buffer.from(sodium.crypto_sign_seed_keypair(rkey).privateKey);
}
}
self._key = rkey;
return done();
});
}
return sodium.ready.then(() => {
if (self.protocol() instanceof V2) {
if (!(rkey instanceof Buffer)) { return done(new TypeError('Raw key must be provided as a buffer')); }
const len = Buffer.byteLength(rkey);
if (len === sodium.crypto_sign_KEYPAIRBYTES) {
rkey = rkey.slice(0, sodium.crypto_sign_SECRETKEYBYTES);
} else if (len !== sodium.crypto_sign_SECRETKEYBYTES) {
if (len !== sodium.crypto_sign_SEEDBYTES) {
throw new Error('Secret keys must be 32 or 64 bytes long; ' + len + ' given.')
}
rkey = Buffer.from(sodium.crypto_sign_seed_keypair(rkey).privateKey);
}
}
self._key = rkey;
return done();
});
}
function sign(message, sk, cb) {
if (typeof sk === 'function') {
cb = sk;
sk = null;
}
const done = ret(cb);
let payload, isk;
[ payload ] = iparse(message);
[ sk ] = cparse(sk);
switch (sk && Buffer.byteLength(sk)) {
case sodium.crypto_sign_SECRETKEYBYTES:
isk = sk;
break;
case sodium.crypto_sign_SEEDBYTES:
isk = sodium.crypto_sign_seed_keypair(sk).privateKey;
break;
default:
isk = sodium.crypto_sign_keypair().privateKey;
sk = sodium.crypto_sign_ed25519_sk_to_seed(isk);
}
let signature;
try {
signature = sodium.crypto_sign_detached(payload, isk);
} catch(ex) {
return done(new Error('Libsodium error: ' + ex));
}