Express.js API HTTP转HTTPS失败,报密钥不匹配错误求助
Hey there, let's fix this X509_check_private_key:key values mismatch error you're hitting—it's a classic issue when setting up HTTPS, and the root cause is straightforward: the private key and certificate you're using in your Node.js code don't form a matching pair.
为什么会出现这个错误?
The error tells us that the private key (options.key) you're loading doesn't correspond to the SSL certificate (options.cert) you provided. Looking at your code, I can spot the problem right away:
- You're using
cert.pemas your private key (wrong—this should be your actual private key file) - You're using
ca-certificates.crtas your domain certificate (this is the system's collection of root CA certificates, not your custom SSL cert for the domain)
具体修复步骤
Let's walk through how to get this right:
Locate your correct AWS SSL files
When you get an SSL certificate from AWS, you should have at least three files (depending on the type):- Your domain's primary certificate (e.g.,
mydomain.crt) - AWS's intermediate certificate chain (e.g.,
aws-chain.crt) - The private key file you generated when requesting the certificate (e.g.,
private-key.pem—this is the one you used to create the CSR)
- Your domain's primary certificate (e.g.,
Update your Node.js code
Fix theoptionsobject to point to the correct files, and make sure HTTP/HTTPS listen on different ports (you can't have both on 8081):var fs = require('fs'); // Don't forget to import fs—your original code missed this! var http = require('http'); var https = require('https'); var options = { key: fs.readFileSync('/path/to/your/private-key.pem', { passphrase: 'XXXXX' }), // Your actual private key cert: fs.readFileSync('/path/to/your/mydomain.crt'), // Your domain's SSL certificate ca: fs.readFileSync('/path/to/aws-chain.crt') // Include the intermediate chain to avoid browser trust issues }; var httpServer = http.createServer(app); var httpsServer = https.createServer(options, app); httpServer.listen(8080); // Use a separate port for HTTP httpsServer.listen(8443); // HTTPS typically uses 443, but 8443 is fine for development/testingVerify the key and certificate match
To double-check they're a valid pair, run these OpenSSL commands in your terminal:# Get the modulus of your certificate openssl x509 -noout -modulus -in mydomain.crt | openssl md5 # Get the modulus of your private key openssl rsa -noout -modulus -in private-key.pem | openssl md5If the two MD5 outputs are identical, your key and cert are a matching pair—if not, you're using the wrong files.
Check file permissions
Make sure the Node.js process has read access to your certificate and key files. You can adjust permissions with:chmod 644 /path/to/your/cert-and-key-files/*
内容的提问来源于stack exchange,提问作者Senthil

