📜  Node.js crypto.verify()函数

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

Node.js crypto.verify()函数

crypto.verify()是 node.js 加密内置模块的一种方法,用于验证使用不同类型的散列函数(如 SHA256 算法等)散列的数据的签名。

句法:

crypto.verify(algorithm, data, publicKey, signature)

参数:

  • 算法:它是一个字符串类型的值。可以通过应用签名算法的名称来验证签名,例如“SHA256”。算法必须与创建签名的算法相同。
  • 数据:数据参数必须是缓冲区、类型化数组或数据视图的实例。
  • key:应该是key对象的公钥。如果您没有任何公钥,那么您可以使用 crypto.generateKeyPairSync() 方法创建私钥和公钥。
  • 签名:签名参数必须是 Buffer、Typed Array 或 Data View 的实例。

返回值:此函数返回一个布尔值。如果验证签名,则返回True否则返回false

例子:

文件名:index.js

Javascript
// Importing Required Modules
const crypto = require('crypto');
const buffer = require('buffer');
 
// Creating a private key
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});
// Using Hashing Algorithm
const algorithm = "SHA256";
 
// Converting string to buffer
const data = Buffer.from("I Love GeeksForGeeks");
 
// Sign the data and returned signature in buffer
const signature = crypto.sign(algorithm, data , privateKey);
 
// Verifying signature using crypto.verify() function
const isVerified = crypto.verify(algorithm, data, publicKey, signature);
 
// Printing the result
console.log(`Is signature verified: ${isVerified}`);


使用以下命令运行index.js

node index.js

输出:

参考:https://nodejs.org/api/crypto.html#crypto_crypto_verify_algorithm_data_key_signature