Node.js x509.checkIP(ip[, options]) Method
Last Updated :
26 Mar, 2021
The x509.checkIP() is an inbuilt application programming interface of class X509Certificate within crypto module which is used to check if this PEM encoded X509 Certificate matches the given IP address or not.
Syntax:
const x509.checkIP(ip[, options])
Parameters: This method takes the following arguments as the parameter.
- ip: It holds ip address
- options: Any option which will affect this api operation.
Return Value: This method returns the ip if it matches with the certificate host name otherwise it will return undefined.
How to generate a Public certificate?
Public certificate Open notepad and copy-paste the following key and save the file as 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-----
Example 1:
index.js
const {X509Certificate} = require( 'crypto' )
const fs = require( 'fs' )
const x509 = new X509Certificate(fs.readFileSync( 'public-cert.pem' ));
const value = x509.checkIP( "2409:4060:2e05:28d2:d02:7717:820b:22ef" )
if (value)
console.log( "IP address matched" )
else
console.log( "IP address did't match" )
|
Run the index.js file using the following command.
node index.js
Output:
IP address did't match
Example 2:
index.js
const {X509Certificate} = require( 'crypto' )
const fs = require( 'fs' )
if (( new X509Certificate(fs.readFileSync( 'public-cert.pem' ))).checkIP( "2409:4060:2e05:28d2:d02:7717:820b:22ef" ))
console.log( "IP address matched" )
else
console.log( "IP address did't match" )
|
Run the index.js file using the following command.
node index.js
Output:
IP address did't match
Reference: https://nodejs.org/dist/latest-v15.x/docs/api/crypto.html#crypto_x509_checkip_ip_options
Share your thoughts in the comments
Please Login to comment...