Language: EN

criptografia-en-nodejs

Cryptographic Functions in Node.js with Crypto

The crypto module of Node.js provides a wide range of functions for working with cryptography, from generating hashes to encrypting and decrypting data.

Crypto Module Functions

Generate a Hash from a String

To generate a hash from a string, you can use the crypto module along with the desired hash algorithm, such as SHA-256. Here’s an example of how to do it:

import { createHash } from 'node:crypto';

const string = 'Message to hash';

const hash = createHash('sha256');
hash.update(string);

const hashResult = hash.digest('hex');
console.log('SHA-256 Hash:', hashResult);

Generate a Hash from a Password with Salt

When it comes to securely storing passwords, it’s important to use techniques such as hashing passwords with salt.

Bcrypt is a popular library that facilitates this process. Let’s see how to generate and compare password hashes with Bcrypt:

import { hashSync, compareSync, genSaltSync } from 'bcrypt';

const password = 'password123';

// Generate hash with salt
const saltRounds = 10;
const salt = genSaltSync(saltRounds);
const hash = hashSync(password, salt);

console.log('Password Hash:', hash);

// Compare hash with entered password
const correctPassword = 'password123';
const comparisonResult = compareSync(correctPassword, hash);
console.log('Passwords match:', comparisonResult);

Generate an RSA Key Pair

The RSA encryption algorithm is widely used for asymmetric encryption. We can generate an RSA key pair with the crypto module as follows:

import { generateKeyPairSync } from 'node:crypto';

const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

console.log('RSA Public Key:', publicKey);
console.log('RSA Private Key:', privateKey);

Encrypt and Decrypt Data Using RSA

With the generated RSA keys, we can securely encrypt and decrypt data. Here’s an example of how to do it:

import { publicEncrypt, privateDecrypt } from 'node:crypto';

const message = 'Message to encrypt';

// Encrypt with public key
const encryptedMessage = publicEncrypt(publicKey, Buffer.from(message, 'utf8'));
console.log('Encrypted Message:', encryptedMessage.toString('base64'));

// Decrypt with private key
const decryptedMessage = privateDecrypt(privateKey, encryptedMessage);
console.log('Decrypted Message:', decryptedMessage.toString('utf8'));