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


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

x509.verify() 是加密模塊中 X509Certificate 類的內置應用程序編程接口,用於檢查證書是否由給定的公鑰簽名。

用法:

const x509.verify(publicKey)

參數:該函數將公鑰對象作為參數。

返回值:當且僅當證書由給定的公鑰簽名時,此函數才返回布爾值 true。

如何生成公共證書?



公用證書:打開記事本並使用copy-paste和以下 key 並將文件另存為public-cert.pem

-----BEGIN CERTIFICATE-----
MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV
BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG
9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw
OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw
DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM
Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB
nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm
Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi
QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC
kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX
bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG
BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC
hWF6W2H9+MAlU7yvtmCQQuZmfQ==
-----END CERTIFICATE-----

範例1:

文件名:index.js

Javascript


// Node.js program to demonstrate the 
// x509.verify() function
// Importing crypto module
const {X509Certificate} = require('crypto')
// Importing fs module
const fs = require('fs')
// getting object of a PEM encoded X509 Certificate.
const x509 = new X509Certificate(fs.readFileSync('public-cert.pem'));
// checking if this certificate is signed by the given public key or not
// by using x509.verify() function
const value = x509.verify(x509.publicKey)
// display the result
if(value)
console.log("certificate is signed by the given public key")
else
console.log("certificate is not signed by the given public key")

使用以下命令運行index.js文件。

node index.js

輸出:

certificate is signed by the given public key

範例2:

文件名:index.js

Javascript


// Node.js program to demonstrate the 
// x509.verify() function
// Importing crypto module
const {X509Certificate} = require('crypto')
// Importing fs module
const fs = require('fs')
// display the result
if((new X509Certificate(fs.readFileSync('public-cert.pem')))
    .verify((new X509Certificate(fs.readFileSync('public-cert.pem'))).publicKey))
console.log("certificate is signed by the given public key")
else
console.log("certificate is not signed by the given public key")

使用以下命令運行index.js文件。

node index.js

輸出:

certificate is signed by the given public key

參考:https://nodejs.org/dist/latest-v15.x/docs/api/crypto.html#crypto_x509_publickey




相關用法


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