crypto-helper/lib/random.js

47 lines
870 B
JavaScript
Raw Normal View History

'use strict';
const crypto = require ('crypto');
/**
* creates a random string
*
* @param {number} len string length default: 8
* @returns {string} random string
*/
function random_string (len = 8) {
if (len < 1)
throw new Error ('invalid length');
return crypto.randomBytes (Math.ceil (len * 3 / 4))
.toString ('base64')
.substr (0, len);
}
/**
* creates a random hexadecimal string
*
* @param {number} len length
* @returns {string} hex string
*/
function random_hex (len = 8) {
if (len < 1)
throw new Error ('invalid length');
return crypto.randomBytes (Math.ceil (len / 2))
.toString ('hex')
.substr (0, len);
}
/**
* creates a 64 character long random hex string
*
* @returns {string} salt
*/
function create_salt () {
return random_hex (64);
}
module.exports = {
create_salt,
random_hex,
random_string
};