基于node-forge跨平台获取证书指纹的技术求助
Alright, let's break down how to use node-forge to grab certificate fingerprints for your cross-platform app when making requests to domains like www.anydomain.com. I'll cover the two main scenarios you might be working in, since the approach varies a bit depending on your environment.
First: Set up node-forge
First, make sure you've got the forge.min.js file you referenced included in your project:
- For browser/front-end use: Add a
<script>tag pointing to the file in your HTML. - For Node.js/Electron: Use
require()to import the file from its path in your project.
Scenario 1: Node.js/Electron Environment (Direct TLS Access)
If you're working in Node.js (including Electron's main process), you can directly fetch the server's certificate when making HTTPS requests, then use node-forge to extract the fingerprint. Here's a working example:
const forge = require('./path/to/forge.min.js'); // Update this path to your file const https = require('https'); function fetchCertificateFingerprint(domain) { return new Promise((resolve, reject) => { const request = https.get(`https://${domain}`, (response) => { // Grab the raw certificate from the connection const serverCert = response.socket.getPeerCertificate(); if (!serverCert.raw) { reject(new Error("Couldn't retrieve raw certificate data")); return; } // Convert the raw certificate to a format node-forge can parse const certDer = forge.util.decode64(serverCert.raw.toString('base64')); const parsedCert = forge.pki.certificateFromAsn1(forge.asn1.fromDer(certDer)); // Calculate the SHA-256 fingerprint (more secure than SHA-1) const hash = forge.md.sha256.create(); hash.update(parsedCert.toDer()); const fingerprint = hash.digest().toHex().toUpperCase().match(/.{2}/g).join(':'); resolve(fingerprint); }); request.on('error', (err) => reject(err)); request.end(); }); } // Usage example fetchCertificateFingerprint('www.anydomain.com') .then(fingerprint => { console.log('SHA-256 Certificate Fingerprint:', fingerprint); // Use this fingerprint in your business logic (e.g., validate before fetching data) }) .catch(error => { console.error('Error getting fingerprint:', error); });
A few notes here:
- We use SHA-256 for the fingerprint — SHA-1 is outdated and insecure, so stick with stronger hashes like SHA-256 or SHA-512.
- The fingerprint is formatted into the common colon-separated hex format (e.g.,
A1:B2:C3...) for readability and compatibility.
Scenario 2: Browser Environment (Front-End Ajax)
Browsers block front-end JavaScript from accessing TLS certificates directly for security reasons. So you'll need a simple backend proxy to handle the certificate fetching for you:
- Build a backend endpoint: Use the Node.js code from Scenario 1 to create an API endpoint that accepts a domain parameter and returns its certificate fingerprint.
- Call the endpoint from your front-end: Use Ajax/fetch to get the fingerprint, then use it in your business logic.
Front-end example code:
// Replace with your backend endpoint URL fetch(`/api/get-cert-fingerprint?domain=www.anydomain.com`) .then(res => res.json()) .then(data => { console.log('Certificate Fingerprint:', data.fingerprint); // Proceed with your data requests once you've validated the fingerprint }) .catch(err => { console.error('Failed to fetch fingerprint:', err); });
Bonus: Full Certificate Validation (If Needed)
If your business logic requires more than just a fingerprint (like checking the certificate's expiration date or issuer), you can use node-forge's built-in tools to parse and validate the full certificate chain. For example:
// After parsing the certificate into parsedCert (from Scenario 1) console.log('Certificate Expires:', parsedCert.validity.notAfter); console.log('Issued By:', parsedCert.issuer.getField('CN').value);
内容的提问来源于stack exchange,提问作者Himmat Singh

