Last active
October 14, 2020 13:01
-
-
Save EnzoDiazDev/a77cbdd73694cc32a03913ddfc562d0c to your computer and use it in GitHub Desktop.
Generates a cryptographically secure pseudorandom number from 0 to 255. Written in typescript (javascript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//MIT license. | |
/** | |
* @file Considering that using PRNG is not secure, | |
* this function provides a cryptographically secure random integer (CSPRNG). | |
*/ | |
import { randomBytes } from 'crypto'; | |
/** | |
* Generates a cryptographically secure pseudorandom number from 0 to 255, | |
* as specified by (`min`,`max`) | |
* @param {number} min A minimum expected number ─ *default: `0`* | |
* @param {number} max A maximum expected number ─ *default: `255`* | |
*/ | |
export default function randomUint8(min = 0, max = 255): number { | |
//parameters check | |
if (min === max) { | |
return max; | |
} | |
if (min > max) { | |
const minAux = min; //auxiliary const | |
min = max; | |
max = minAux; | |
} | |
if (max > 255) { | |
max = 255; | |
} | |
const randomByte: number = randomBytes(1)[0]; | |
if(min === 0 && max === 255){ | |
return randomByte; | |
} | |
const range = max - min + 1; | |
const max_range = 256; | |
if (randomByte >= Math.floor(max_range / range) * range) { | |
return randomUint8(min, max); | |
} | |
return min + (randomByte % range); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Otra versión en Javascript