Certificate management
Basic Concepts of Certificate Management
Certificate management in Node.js primarily involves the generation, verification, storage, and usage of digital certificates. Digital certificates typically adhere to the X.509 standard format and contain critical data such as public keys, holder information, issuer details, and validity periods. Certificate management is a core component in scenarios like HTTPS communication, API authentication, and data encryption.
const fs = require('fs');
const crypto = require('crypto');
// Example of generating a self-signed certificate
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
Certificate Generation and Issuance
Node.js can generate certificates through the crypto
module. Common methods include self-signed certificates and CA-issued certificates. Self-signed certificates are suitable for development and testing environments, while production environments typically require certificates issued by a trusted Certificate Authority (CA).
const forge = require('node-forge');
// Generating a CSR using node-forge
const keys = forge.pki.rsa.generateKeyPair(2048);
const csr = forge.pki.createCertificationRequest();
csr.publicKey = keys.publicKey;
csr.sign(keys.privateKey);
// Converting CSR to PEM format
const pem = forge.pki.certificationRequestToPem(csr);
Certificate Verification Mechanisms
Certificate verification includes chain validation, validity period checks, and CRL/OCSP checks. Node.js's tls
module has built-in certificate verification functionality, which can be customized via parameters.
const https = require('https');
const tls = require('tls');
const options = {
host: 'example.com',
port: 443,
method: 'GET',
checkServerIdentity: (host, cert) => {
// Custom verification logic
if (cert.subject.CN !== host) {
return new Error('Certificate hostname mismatch');
}
}
};
Certificate Storage Solutions
Certificate storage requires consideration of security and accessibility. Common storage methods include:
- File system storage
- Database storage
- Key Management Systems (KMS)
- Hardware Security Modules (HSM)
// Example of storing a private key using AWS KMS
const AWS = require('aws-sdk');
const kms = new AWS.KMS();
const params = {
KeyId: 'alias/my-key',
Plaintext: 'my-private-key-data'
};
kms.encrypt(params, (err, data) => {
if (err) console.log(err);
else console.log(data.CiphertextBlob);
});
Certificate Rotation Strategies
Certificate rotation is a critical aspect of security operations. The following factors must be considered:
- Early renewal time window
- Overlap period for old and new certificates
- Automated deployment processes
- Rollback mechanisms
// Example of an automated certificate rotation script
const cron = require('node-cron');
const acme = require('acme-client');
cron.schedule('0 3 * * *', async () => {
const client = new acme.Client({
directoryUrl: acme.directory.letsencrypt.production
});
const cert = await client.auto({
csr: await forge.createCsr(),
email: 'admin@example.com',
termsOfServiceAgreed: true
});
fs.writeFileSync('/path/to/cert.pem', cert.certificate);
});
Certificate Revocation Handling
When a certificate's private key is compromised or no longer needed, the certificate should be revoked promptly. Node.js can perform real-time certificate status checks via the OCSP protocol.
const ocsp = require('ocsp');
const server = ocsp.Server.create({
cert: fs.readFileSync('server.crt'),
key: fs.readFileSync('server.key')
});
server.addCert('serial', 'issuer', {
status: 'revoked',
reason: 'keyCompromise',
revocationTime: new Date()
});
server.listen(8080);
Multi-Domain Certificate Management
SAN (Subject Alternative Name) certificates can include multiple domains, which require special handling.
const san = {
altNames: [
{ type: 2, value: 'example.com' },
{ type: 2, value: 'www.example.com' },
{ type: 2, value: 'api.example.com' }
]
};
const cert = forge.pki.createCertificate();
cert.setSubject([{ name: 'commonName', value: 'example.com' }]);
cert.setExtensions([{
name: 'subjectAltName',
altNames: san.altNames
}]);
Certificate Monitoring and Alerts
Establishing a certificate monitoring system can prevent service disruptions due to expired certificates.
const checkCertExpiry = (certPath) => {
const cert = fs.readFileSync(certPath);
const parsed = forge.pki.certificateFromPem(cert);
const expiry = parsed.validity.notAfter;
const daysLeft = Math.floor((expiry - new Date()) / (1000 * 60 * 60 * 24));
if (daysLeft < 30) {
sendAlert(`Certificate will expire in ${daysLeft} days`);
}
};
Security Best Practices for Certificates and Keys
- Private keys must be stored encrypted
- Set appropriate file permissions
- Avoid committing certificates to version control systems
- Use environment variables to manage sensitive information
// Example of setting file permissions
fs.chmodSync('private.key', 0o600);
fs.chmodSync('certificate.pem', 0o644);
// Using dotenv to manage environment variables
require('dotenv').config();
const key = process.env.SSL_KEY;
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn