Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse x509 certificate string in node

I need to parse an x509 certificate string using node.js (preferably natively via the crypto api). I need to do this so I can get an object which contains the certificate's expiry date, so I know when to automatically renew it.

I can't figure out where to begin

Here is an example certificate I am trying to parse

-----BEGIN CERTIFICATE-----
MIIDqDCCApCgAwIBAgICKg8wDQYJKoZIhvcNAQELBQAwWjELMAkGA1UEBhMCVVMx
EzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxJDAiBgNVBAoT
G2dldGFDZXJ0IC0gd3d3LmdldGFjZXJ0LmNvbTAeFw0xOTExMDYwNjMwNDNaFw0y
MDAxMDUwNjMwNDNaMIGJMQswCQYDVQQGEwJBVTELMAkGA1UECBMCU0ExGjAYBgNV
BAcTEVJvc3RyZXZvciBTQSA1MDAwMRAwDgYDVQQKEwdDb3JzdGV4MRcwFQYDVQQD
Ew5BbGJlcnQgTWFyYXNoaTEmMCQGCSqGSIb3DQEJARYXYWxiZXJ0bWFzaHlAb3V0
bG9vay5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCdPRTB3j6k
XeylM4Tf7+s7YtjnGgc8Zseh4nX22xpo+sE+pYvOLu4NexprToJ64Yi/SMmBk9u2
0EkrvhWVkA1n8VyU6Oh57Oeg7cDMkqoabJ2CJBn/Z5AF3xrE9GYoymGsfHThd6nQ
JD/HRcErWGyAEwbnNG5CpwySVrMHo2A5va4pDwiDqQAf5rNLP0swtV7Q6UC6eJXs
I5Gbv3bhD8i44DLkj6rbY8uWClhns5XSG5R+rTwoYHkLolLPLj6Em7QtJKPyDsp1
6lzsjLsgzmRixFDhqI3HUlGUnAu6gwwxvP53qhSUi88sKe4M37med5HSAxv+U7A9
rr1js4ey84/9AgMBAAGjSDBGMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTw
MAsGA1UdDwQEAwIFIDAZBgNVHREEEjAQgg5BbGJlcnQgTWFyYXNoaTANBgkqhkiG
9w0BAQsFAAOCAQEAnXQAvyYE10bc5V9AsjT4x8xyI5AZ6su9OXEDuBFQi2UGvwtb
hhrBZ79Y3KfomXmwtHNVzo6V7dG+9yoDykaKb/Ub72VqF9ZKZArgglMFlGhAk90c
msxWGm7sHLBlt2yjkvnAtt1EtnbOtmuPNGOA7yALTN9/uzBPoTgkjuI1Fkb1uHc1
gynJpqrT0r/qJp0aDxO2SokWYzv/SRCfQTeLMZ5dctHWb8UnsEzt578zYmlDwVof
tOniZVO5TwnXCaWOPjG9XKbW6wHUyMWbulxM9SJUeIjFI2ipQuW8O7Vd94aEyH8o
lc8zFSWoNxamcoX+4ajrs9VbNXythJ91UAtvtA==
-----END CERTIFICATE-----
like image 405
Dominus Vilicus Avatar asked Dec 18 '22 15:12

Dominus Vilicus


2 Answers

Since nodejs 15.6, you would better use the standard crypto module: https://nodejs.org/api/crypto.html#x509validto

const crypto = require("crypto")
const cert = new crypto.X509Certificate(fs.readFileSync('my.crt')))

console.log(cert.validTo)
// Gives 'Feb  4 10:37:22 2027 GMT'
like image 89
Benjam Avatar answered Jan 07 '23 15:01

Benjam


The node-forge package can parse X.509 certificates and return the parsed certificate in object form, including expiry data:

const forge = require('node-forge')

const cert = forge.pki.certificateFromPem(pem)

cert.validity.notAfter // => 2020-01-05T06:30:43.000Z
like image 26
Dominus Vilicus Avatar answered Jan 07 '23 14:01

Dominus Vilicus