Node.js 解释crypto模块的使用

Node.js 解释crypto模块的使用

在本文中,我们将探讨crypto模块及其在Node.js中的用途。Node.js支持大量的第三方模块。这些模块可以用于执行不同类型的任务。crypto模块也是一个可以导入和在Node.js中使用的第三方模块。该模块可以用于加密、解密或对任何类型的数据进行哈希处理。这种加密和解密基本上有助于保护数据并添加身份验证的层次。crypto模块的主要用例是将普通可读文本转换为加密格式,并在需要时解密。

Crypto和ByCrypto是两个不同的第三方模块,可用于保护敏感数据。Crypto和ByCrypto之间的主要区别在于ByCrypto提供比Crypto模块更强大的哈希功能。

普通文本以人类可读的形式存在,通常由字母和单词组成。使用crypto模块加密此文本后,它将被更改为计算机可读的格式。例如:sdfasc1asT67W2sqWwsdfsadf

加密机制:

哈希: 在此机制中,一系列普通文本基本上转换为密文。这是一种单向的加密算法,因为我们无法将这个密文再次转换为普通文本。此方法通常在用户对系统进行身份验证时使用,同时提供敏感密码。由于无法存储密码,因此将存储这些密文。一些常用的哈希算法是:消息摘要5(MD5),RSA,SHA等是常用的哈希算法。

加密和解密: 在此机制中,一系列普通文本通过秘密密钥转换为加密文本,然后使用相同的密钥进行解密。加密文本无法在没有秘密密钥的情况下转换为原始文本。此算法接受加密文本和秘密密钥的输入,并将原始文本作为输出返回。此机制在消息系统中广泛用于防止网络泄漏数据。一些常用的机制是AES,DES等。

功能:

  • 使用简便
  • 广泛使用的算法,提供多种加密和解密选项
  • 更清晰和一致的代码
  • 可以轻松与Node.js中的Javascript代码集成

    安装模块:

npm install crypto-js --save

示例1: 使用来自crypto-js模块的SHA256。

// Importing module
const SHA256 = require("crypto-js/sha256");
 
// Initializing the original data
const originalData = "Welcome To GeeksForGeeks"
 
// Hashing the Original data
const hasheddata = SHA256(originalData).toString()
 
// Printing hashed data
console.log("Hashed Data is: " + hasheddata)

输出:

Hashed Data is: ecf0cc86124bb4191a1a10f48b1eb2a7b3b3c7aa8c38ac8de8ad6c0a1502b985

示例2: 使用加密模块对数据进行加密和解密。我们可以使用一个密钥进行加密,然后同样的密钥进行解密。

// Importing the crypto module
const crypto = require("crypto-js")
 
// Initializing the original data
const data = "This is the data that need to be encrypted"
 
// Defining the secret key
const key = "pwd@1234"
 
// Encrypting the data using the password key
const encrypted = crypto.AES.encrypt(data, key).toString();
console.log("Encrypted data -- ")
 
// Printing the encrypted data
console.log(encrypted)
console.log("Decrypted data -- ")
 
// Decrypting the data using the same password key
const decrypted = crypto.AES.decrypt(encrypted, key)
    .toString(crypto.enc.Utf8)
console.log(decrypted)

输出:

Node.js 解释crypto模块的使用

参考: https://www.npmjs.com/package/crypto-js

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程