UNPKG

domotz-remote-pawn

Version:

Domotz Agent

72 lines (59 loc) 2.3 kB
/** This file is part of Domotz Agent. * Copyright (C) 2016 Domotz Ltd * * Domotz Agent is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Domotz Agent is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>. **/ /** * Created by Tommaso Latini <tommaso@domotz.com> on 28/12/15. */ const MODULE = 'RANDOM'; var factory = function (crypto) { function md5(data) { return crypto.createHash('md5').update(data).digest("hex"); } function getRandomBytes(n, encoding) { var randomStr; try { var rnd = crypto.randomBytes(n); randomStr = rnd.toString(encoding); console.debug('%s - Have %d bytes of random data', MODULE, rnd.length, rnd); } catch (ex) { console.error(ex.stack); // most likely, entropy sources are drained throw(ex); } return randomStr; } function randomNumberFromString(str, start, end){ var currentVal, res = start, range = end - start + 1, input = md5(str); console.verbose('%s - Input: %s. Original String: %s. Range: %s', MODULE, input, str, range); for(var i = 0; range >= 1.0; i++) { currentVal = parseInt(input.charAt(i), 16); range = range/16.0; res += currentVal * range; console.silly('%s - %s] Range: %s. Current Value: %s', MODULE, i+1, range, currentVal); } var number = Math.round(res); console.debug('%s - Obtain pseudo random number %s from %s to %s', MODULE, number, start, end); return number; } return { md5: md5, getRandomBytes: getRandomBytes, randomNumberFromString: randomNumberFromString }; }; module.exports.factory = factory;