// https://github.com/digitalbazaar/forge#x509
// npm install node-forge
// https://127.0.0.1:443
const https = require('https')
, forge = require('node-forge');
// Generate certificate
const keyPair = forge.pki.rsa.generateKeyPair(2048)
, cert = forge.pki.createCertificate()
, now = new Date()
, oneYear = new Date(new Date(now).setFullYear(now.getFullYear() + 1));
Object.assign(cert, {
publicKey: keyPair.publicKey
, serialNumber: '01'
, validity: {
notBefore: now
, notAfter: oneYear
}
});
cert.sign(keyPair.privateKey, forge.md.sha256.create()); // self signed
const serverPrivateKeyPem = forge.pki.privateKeyToPem(keyPair.privateKey)
, serverPublicKeyPem = forge.pki.publicKeyToPem(keyPair.publicKey)
, serverCertificatePem = forge.pki.certificateToPem(cert);
// Server
const serverOptions = {
key: serverPrivateKeyPem
, cert: serverCertificatePem
};
const server = https.createServer(serverOptions, function (request, response) {
response.writeHead(200, 'OK', {'Content-Type': 'text/plain'});
response.end('Hello World!');
})
server.listen(443, '127.0.0.1', function () {
console.log('Server started at https://127.0.0.1:443');
});
// Client
const clientOptions = {
hostname: '127.0.0.1'
, port: 443
, path: '/'
, method: 'GET'
, rejectUnauthorized: false // don't check certificate
, requestCert: true
, agent: false
};
const client = https.request(clientOptions, function (response) {
response.on('data', function (data) {
console.log(data.toString());
});
response.on('end', function () {
server.close();
});
});
client.on('error', function (error) {
throw error;
});
client.end();
Комментариев нет:
Отправить комментарий