вторник, 12 сентября 2017 г.

Node.js TLS Socket connection full example

// https://github.com/digitalbazaar/forge#x509
// npm install node-forge

const tls = require('tls')
        , 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 = tls.createServer(serverOptions, function (socket) {
    console.log('Insecure connection 2');
    // socket.authorized will be true if the client cert presented validates with our CA
    console.log('Client connected to Server. Client ' + (socket.authorized ? 'authorized' : 'unauthorized'));
    socket.setEncoding('utf8');
    socket.on('data', function (data) {console.log(data.toString());});
    socket.on('end', function () {console.log('END');});
    socket.write('Hello');
    socket.end('World');
});

server.on('connection', function (socket) {
    console.log('Insecure connection 1');
})

server.on('secureConnection', function (socket) {
    // socket.authorized will be true if the client cert presented validates with our CA
    console.log('Secure connection. Client authorized: ' + socket.authorized);
});

server.listen(8000, '127.0.0.1', function () {
    console.log('Server started at https://127.0.0.1:443');
});

// Client

const clientOptions = {
      key: serverPrivateKeyPem
    , cert: serverCertificatePem
    , rejectUnauthorized: false
};

const client = tls.connect(8000, '127.0.0.1', clientOptions, function () {
    if (client.authorized) {
        console.log('Connection authorized by a Certificate Authority.');

        client.write('GET /hey HTTP/1.1\r\n');
        client.write('\r\n');

        client.write('POST /ho HTTP/1.1\r\n');
        client.write('\r\n');

    } else {
        console.log('Connection not authorized: ' + client.authorizationError);

        client.write('We are not authorized');

    }
});

client.setEncoding('utf8');

client.on('data', function (data) {
    console.log(data.toString());
});

client.on('end', function (data) {
    server.close();
});

client.on('close', function() {
    console.log('SOCKET CLOSED');
});

Комментариев нет:

Отправить комментарий