Skip to content

Instantly share code, notes, and snippets.

@EnzoDiazDev
Last active October 14, 2020 13:01
Show Gist options
  • Save EnzoDiazDev/a77cbdd73694cc32a03913ddfc562d0c to your computer and use it in GitHub Desktop.
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)
//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);
}
@EnzoDiazDev
Copy link
Author

EnzoDiazDev commented Aug 13, 2020

Otra versión en Javascript

//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`*
 * @returns {number}
 */
export default function random_uint8(min = 0, max = 255) {
    //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 = 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 random_uint8(min, max);

    return min + (randomByte % range);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment