📜  讲解Node.js中crypto模块的使用

📅  最后修改于: 2022-05-13 01:56:31.053000             🧑  作者: Mango

讲解Node.js中crypto模块的使用

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

Crypto 和 ByCrypto 是两个不同的第 3 方模块,可用于保护敏感数据。 Crypto 和 ByCrypto 之间的主要区别在于,与 Crypto 模块相比,ByCrypto 提供了更强大的散列。

纯文本是人类可读的形式,通常由字母和单词组成。使用 Crypto 模块加密此文本后,它将更改为计算机可读格式。例如:像这样的东西:sdfasc1asT67W2sqWwsdfsadf

密码机制:

Hashing:在这种机制下,一系列的明文基本上都被转换成密文。这是一种单向密码算法,因为我们无法再次将此密文转换为纯文本。这种方法基本上是在系统的用户认证过程中使用,同时提供敏感密码。由于无法存储密码,因此将存储这些密文。一些流行的散列算法有:Message Digest 5(MD5)、RSA、SHA 等是广泛使用的散列算法。

加密和解密:在这种机制中,一系列纯文本在密钥的帮助下转换为加密文本,然后使用相同的密钥解密。没有密钥,加密文本无法转换为原始文本。该算法采用加密文本的输入和将原始文本作为输出返回的密钥。这种机制主要用于消息系统中,以防止网络发生任何类型的数据泄漏。一些流行的机制是 AES、DES 等。

特征:

  • 使用方便
  • 广泛使用的算法,具有多种加密和解密选项
  • 更简洁一致的代码
  • 可以很容易地与 NodeJS 中的 Javascript 代码集成

安装模块:

npm install crypto-js --save

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

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


Javascript
// Importing the crypto module
const crypto=require("crypto-js")
  
// Initializing the original data
var data = "This is the data that need to be encrypted"
  
// Defining the secret key
var key = "pwd@1234"
  
// Encrypting the data using the password key
var 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
var decrypted = crypto.AES.decrypt(encrypted, key)
  .toString(crypto.enc.Utf8)
console.log(decrypted)


输出:

Hashed Data is: ecf0cc86124bb4191a1a10f48b1eb2a7b3b3c7aa8c38ac8de8ad6c0a1502b985

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

Javascript

// Importing the crypto module
const crypto=require("crypto-js")
  
// Initializing the original data
var data = "This is the data that need to be encrypted"
  
// Defining the secret key
var key = "pwd@1234"
  
// Encrypting the data using the password key
var 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
var decrypted = crypto.AES.decrypt(encrypted, key)
  .toString(crypto.enc.Utf8)
console.log(decrypted)

输出:

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