Nest.js hashing and encryption example detailed explanation

Nest.js hashing and encryption example detailed explanation

0x0 Introduction

First of all, what is a hash algorithm? An algorithm that produces a hash value for some piece of data, such as a message or session item. For example, md5 is a hashing algorithm. A hash function or hash algorithm in software development, also known as a hash function, is a method of creating a small digital "fingerprint" from any kind of data. All hash functions have a fundamental property: if two hash values ​​are different (according to the same function), then the original inputs to the two hash values ​​are also different.

Encryption algorithms are usually divided into symmetric encryption algorithms and asymmetric encryption algorithms. For symmetric encryption algorithms, both parties receiving the information need to know the key and encryption and decryption algorithm in advance and their keys must be the same. Then the data can be encrypted and decrypted. The asymmetric algorithm is different from this. The sending parties A and B generate a bunch of keys in advance, and then A sends its public key to B, and B sends its public key to A. If A wants to send a message to B, he first needs to use B's public key to encrypt the message, and then send it to B. At this time, B uses its own private key to decrypt the message. The same principle applies when B sends a message to A.

Essentially, hashing and encryption both turn an object into a meaningless string. The difference is that the hashed object cannot be restored and is a one-way process. For example, passwords are usually encrypted using a hashing algorithm, so if a user forgets their password, they can only modify it and cannot obtain the original password. However, the encryption of information is a regular encryption algorithm, and the encrypted information can be decrypted and restored by the secret key.

Hashing and Encryption

Hashing is the process of converting a key value into another key value through a mathematical algorithm. The hash function is used to generate the conversion, and the output content cannot be restored. It is mainly used for password storage when data needs to be hashed.

Encryption is the encoding of information, converting the original information into ciphertext. It is generally used for the client to send sensitive information such as passwords to the server. The information is encrypted before sending and then decrypted on the server.

0x1 Hashing

The Node.js ecosystem has many dependencies, such as Bcrypt and Argon2, which are simple to use. This time, Bcrypt is used to implement the hashing process:

yarn add bcrypt
yarn add @types/bcrypt -D

Then encapsulate the hashed business:

import { Injectable } from '@nestjs/common'
import * as bcrypt from 'bcrypt'

@Injectable()
export class BcryptService {
 private static readonly SALT_ROUNDS: number = 10
 /**
 * Compare and check password * @param rawStr
 * @param hashedStr
 */
 async compare(rawStr: string, hashedStr: string) {
 return bcrypt.compare(rawStr, hashedStr)
 }
 /**
 * Generate hash
 * @param rawStr
 * @param salt
 */
 async hash(rawStr: string, salt?: string) {
 return bcrypt.hash(rawStr, salt || BcryptService.SALT_ROUNDS)
 }
 /**
 * Generate salt */
 async genSalt() {
 return bcrypt.genSalt(BcryptService.SALT_ROUNDS)
 }
}

0x2 Encryption

The Node.js system comes with an encryption module that can be used for encryption and decryption and other related operations. The following uses AES-256-CTR encryption to encrypt data:

import { createCipheriv, randomBytes } from 'crypto'
import { promisify } from 'util'

const iv = randomBytes(16)
const password = 'Password used to generate key'

// The key length depends on the algorithm // In the case of aes256 it is 32 bytes long const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer
const cipher = createCipheriv('aes-256-ctr', key, iv)

const textToEncrypt = 'Nest'
const encryptedText = Buffer.concat([
 cipher.update(textToEncrypt),
 cipher.final()
])

If you need to decrypt it is also very simple:

import { createDecipheriv } from 'crypto'

const decipher = createDecipheriv('aes-256-ctr', key, iv)
const decryptedText = Buffer.concat([
 decipher.update(encryptedText),
 decipher.final()
])

0x3 Reference

Encryption and Hashing

Node.js crypto

node.bcrypt.js

Summarize

This is the end of this article about Nest.js hashing and encryption. For more related Nest.js hashing and encryption content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  Mysql database master-slave separation example code

>>:  Nginx operation and maintenance domain name verification method example

Recommend

Detailed tutorial on installing pxc cluster with docker

Table of contents Preface Preliminary preparation...

Complete steps to upgrade Nginx http to https

The difference between http and https is For some...

Robots.txt detailed introduction

Robots.txt is a plain text file in which website ...

Implementation code for infinite scrolling with n container elements

Scenario How to correctly render lists up to 1000...

MySQL Optimization: InnoDB Optimization

Study plans are easily interrupted and difficult ...

Detailed explanation of html download function

The new project has basically come to an end. It ...

How to use Navicat to operate MySQL

Table of contents Preface: 1. Introduction to Nav...

Tips for Mixing OR and AND in SQL Statements

Today, there is such a requirement. If the logged...

Tutorial on installing MYSQL5.7 from OEL7.6 source code

First, download the installation package from the...

TypeScript decorator definition

Table of contents 1. Concept 1.1 Definition 1.2 D...

How to add Vite support to old Vue projects

1. Introduction I have taken over a project of th...

Example of how to configure nginx to implement SSL

Environmental Description Server system: Ubuntu 1...

A Brief Analysis of Patroni in Docker Containers

Table of contents Create an image File Structure ...