當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js crypto.verify()用法及代碼示例

crypto.verify()是node.js crypto內置模塊的一種方法,用於驗證使用其他類型的哈希函數(例如SHA256算法等)進行哈希處理的數據的簽名。

用法:

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

參數:

  • algorithm: 它是一個string-type值。可以通過應用簽名算法的名稱來驗證簽名,例如“ SHA256”。該算法必須與創建簽名時使用的算法相同。
  • data:data參數必須是緩衝區,類型數組或數據視圖的實例。
  • key:它應該是 key 對象的公鑰。如果沒有任何公鑰,則可以使用crypto.generateKeyPairSync()方法創建私鑰和公鑰。
  • signature:signature參數必須是Buffer,Typed Array或Data View的實例。

返回值:該函數返回一個布爾值。如果簽名經過驗證,則返回True,否則返回false。

例:



index.js


// 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);
  
// Verifing 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

相關用法


注:本文由純淨天空篩選整理自braktim99大神的英文原創作品 Node.js crypto.verify() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。