You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
18 Hrs
35 Min
29 Seg

Manejo de Aleatoriedad en JavaScript

6/25
Resources

How to start a project to generate randomness?

In the programming world, randomness is a fundamental tool for various cryptographic systems and advanced practices. Here I will guide you step by step on how to create a pseudo-random number generation function using Node.js. If you use another programming language, you can opt for the standard libraries it offers. Most of these languages have libraries that allow you to work with these random number generation algorithms.

How to configure the command line in the project?

The first thing you will do is to configure and add a new command in our preconfigured command line. This command will be called prng, which stands for "pseudo random number generation". This name is common in several sources. Below, we add a short description:

const argv = require('yargs/yargs')(process.argv.slice(2)).command('prng', 'Generate a random number', () => {}, (argv) => {}).argv;

This code base will allow you to expand the functionality as needed.

What options can we configure in the builder?

In the builder we will configure the options to customize the generation of numbers:

  1. Randomness type: we will define three main choices:

    • bytes
    • integers
    • UUID identifiers
  2. Size: Essential parameter to determine the length of our cryptographic key. Generally, a default size of 16 bytes is sufficient.

  3. Maximum and minimum number: Applied only for integers, it allows to delimit the range of the generated numbers.

  4. Encoding: Determines how the result will be displayed on the screen. The options are predefined and you can leave them in a configuration file to keep your code clean. The default value is hexadecimal, as it is one of the most manageable formats for this type of project.

How to implement the pseudo-random number generator function?

To begin with, we will create a new folder with a file to implement the functionality. Make sure you have the Node.js crypto library, which is included natively:

const crypto = require('crypto');
function generatorPseudoRandomNumbers(type, size, min, max, encoding) { switch (type) { case 'bytes': return crypto.randomBytes(size).toString(encoding); case 'integers': return crypto.randomInt(min, max).toString(); case 'uuid': return crypto.randomUUID(); default: return null; }}

In this function the desired random type is captured and processed according to the byte, integer or uuid options.

How to handle errors and results on the command line?

Finally, export the function and call it from your command line. Make sure you extract and pass the parameters correctly:

console.log(generatorPseudoRandomNumbers(type, size, min, max, encoding));

Perform the necessary tests and verify that the numbers are generated as expected. It will also be useful to document which options are required for certain types of generation, such as min and max parameters only applicable to integers.

What can you do now?

With this setup you can generate random numbers not only for personal projects, but also in work environments where numbers or secret keys are required. Experiment by trying different input values and expand the capabilities of your project! If you have new ideas for improving the generator, it would be wonderful if you could share them with your colleagues or implement them in your own projects.

Contributions 11

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

**En Node existe la librería** `crypto.getRandomValues()`**:** Genera números aleatorios criptográficamente. Breve ejemplo de uso: ```js const crypto = require('crypto'); const buffer = Buffer.alloc(4); crypto.getRandomValues(buffer); const numeroAleatorio = buffer.readUInt32LE(0); console.log(numeroAleatorio); // 1234567890 ```

CAzadores en la red se convierten en los nuevos héroes, navegando a través de laberintos digitales para encontrar la clave que desactivará la omnipresente IA antes de que su control se vuelva inquebrantable

Hice un fork al repositorio y le agregué algunos comentarios para entenderlo un poco mejor se los comparto ✨ <https://github.com/EloyChavezDev/curso-criptografia>
Yo importé el modulo "secrets" que es parte de una biblioteca estándar de python. este código genera un número aleatorio criptográficamente seguro utilizando import random import secrets ```python import random import secrets # Establecer la semilla para reproducibilidad random.seed(123) # Generar un número aleatorio criptográficamente seguro crypto_random = secrets.token_bytes(16) print("Número aleatorio criptográficamente seguro:", crypto_random) ```
Para aquellos que dependan de generadores de números aleatorios en sus sistemas, les dejo una lista de vulnerabilidades conocidas relacionadas con baja entropía: <https://security.stackexchange.com/a/239397>
Hola Hernesto muchas gracias por esta information yo soy una persona de edad pero estoy encantada con lo que me has ensenado hoy yo vivo and Canada seguire con tu curso pues es facinante Martha
no se ejecutó la librería de yargs ya instale node.js así como tambien npm pero me sigue marcando error mejor lo corri con python con la libreria de secrets.
Para entender el código sobre generación de números aleatorios en JavaScript, necesitas conocimientos en: 1. **JavaScript**: Familiaridad con su sintaxis y estructuras básicas. 2. **Node.js**: Comprender cómo funciona este entorno, ya que el código está diseñado para ejecutarse allí. 3. **Criptografía**: Conocimientos sobre conceptos como aleatoriedad, cifrado y cómo se utilizan las funciones criptográficas para generar valores aleatorios seguros. 4. **Manejo de comandos**: Saber cómo funcionan los argumentos en línea de comandos y cómo se gestionan en scripts. Estos fundamentos te permitirán comprender cada parte del código y su aplicación en sistemas criptográficos.
para esta asignatura es necesario saber programación?
![](https://postimg.cc/1n0xxGsr)![](https://static.platzi.com/media/user_upload/code-2dd28a00-bcae-413f-9be5-fbe9a3bd7a3d.jpg)

Gracias