99 lines
2.3 KiB
JavaScript
Raw Normal View History

'use strict';
const crypto = require ('crypto');
/**
* generate a new rsa keypair
*
* @param {number} length the key length in bit. default: 2048
* @returns {Promise<{public_key: string, private_key: string}>} generated keys
*/
async function generate_keypair (length = 2048) {
const key = await new Promise (
(res, rej) => crypto.generateKeyPair (
'rsa',
{
modulusLength: length,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
},
(err, public_key, private_key) => {
if (err)
rej (err);
res ({ public_key, private_key });
}
)
);
return key;
}
/**
* encrypts data using a public key
* it can only be decrypted with the corresponding private key
*
* @param {string} data data to encrypt
* @param {string} public_key public key
* @returns {string} encrypted data
*/
function asym_encrypt (data, public_key) {
return crypto.publicEncrypt (public_key, Buffer.from (data))
.toString ('base64');
}
/**
* decrypts data using a private key
*
* @param {string} data data to decrypt
* @param {string} private_key private key
* @returns {string} decrypted data
*/
function asym_decrypt (data, private_key) {
return crypto.privateDecrypt (private_key, Buffer.from (data, 'base64'))
.toString ();
}
/**
* creates a signature using a private key
* can later be verified using the corresponding public key
*
* @param {string} data data to sign
* @param {string} private_key private key
* @returns {string} signature
*/
function asym_sign (data, private_key) {
const sign = crypto.createSign ('sha256');
sign.write (data);
sign.end ();
return sign.sign (private_key, 'hex');
}
/**
* verifies a signature using a public key
*
* @param {string} data data to verify
* @param {string} public_key public key
* @param {string} signature signature to verify
* @returns {boolean} true if signature is valid
*/
function asym_verify (data, public_key, signature) {
const verify = crypto.createVerify ('sha256');
verify.write (data);
verify.end ();
return verify.verify (public_key, signature, 'hex');
}
module.exports = {
generate_keypair,
asym_encrypt,
asym_decrypt,
asym_sign,
asym_verify
};