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

ftp remotely connect to Linux via SSH

First install ssh in Linux, taking centos as an e...

A brief discussion on MySQL select optimization solution

Table of contents Examples from real life Slow qu...

CSS+HTML to realize the top navigation bar function

Implementation of navigation bar, fixed top navig...

How to create a stylish web page design (graphic tutorial)

"Grand" are probably the two words that ...

This article will show you what Vite does to the browser's request

Table of contents Working principle: What does th...

MySQL 8.0.12 decompression version installation tutorial personal test!

Mysql8.0.12 decompression version installation me...

A brief analysis of SQL examples for finding uncommitted transactions in MySQL

A long time ago, I summarized a blog post titled ...

Three ways to copy MySQL tables (summary)

Copy table structure and its data The following s...

Java uses Apache.POI to export HSSFWorkbook to Excel

Use HSSFWorkbook in Apache.POI to export to Excel...

The presentation and opening method of hyperlink a

<br />Related articles: How to prompt and op...

How to insert a link in html

Each web page has an address, identified by a URL...

Implementation of breakpoint resume in Node.js

Preface Normal business needs: upload pictures, E...

Analysis of the methods of visual structure layout design for children's websites

1. Warm and gentle Related address: http://www.web...

Detailed tutorial on installing Docker and docker-compose suite on Windows

Table of contents Introduction Download and insta...