Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js https pem error: routines:PEM_read_bio:no start line

I am messing with login form right now with node.js, I tried creating a pem key and csr using

openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

However I been getting errors for running node server.js

Here is my server.js

var http = require('http'),
    express = require('express'),
UserServer = require('./lib/user-server');

var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('./key.pem', 'utf8'),
  cert: fs.readFileSync('./csr.pem', 'utf8')
};

var app = express();

app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

var httpserver = http.createServer(app).listen('3004', '127.0.0.1');
var https_server = https.createServer(options, app).listen('3005', '127.0.0.1');
UserServer.listen(https_server);

Here is the error

crypto.js:104
  if (options.cert) c.context.setCert(options.cert);
                          ^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Object.exports.createCredentials (crypto.js:104:31)
    at Server (tls.js:1107:28)
    at new Server (https.js:35:14)
    at Object.exports.createServer (https.js:54:10)

I tried running

openssl x509 -text -inform DER -in key.pem

It gives

unable to load certificate
140735208206812:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1319:
140735208206812:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509

I am not exactly sure what does the error mean as my encryption file is .pem file already, so any help would be much appreciated.

Thanks

like image 458
xbd Avatar asked Mar 22 '14 22:03

xbd


4 Answers

You are probably using the wrong certificate file, what you need to do is generate a self signed certificate which can be done as follows

openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

then use the server.crt

   var options = {
      key: fs.readFileSync('./key.pem', 'utf8'),
      cert: fs.readFileSync('./server.crt', 'utf8')
   };
like image 66
Hassaan Avatar answered Oct 19 '22 02:10

Hassaan


I removed this error by write the following code

Open Terminal

  1. openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

  2. openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

Now use the server.crt and key.pem file

app.js or server.js file

var https = require('https');
var https_options = {
  key: fs.readFileSync('key.pem', 'utf8'),
  cert: fs.readFileSync('server.crt', 'utf8')
};

var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);

It works but the certificate is not trusted. You can view the image in image file.

enter image description here

like image 41
VIKAS KOHLI Avatar answered Oct 19 '22 03:10

VIKAS KOHLI


For me the issues was I had the key and cert swapped.

var options = {
   key: fs.readFileSync('/etc/letsencrypt/live/mysite.com/privkey.pem'),
   cert: fs.readFileSync('/etc/letsencrypt/live/mysite.com/fullchain.pem'),
   ca: fs.readFileSync('/etc/letsencrypt/live/mysite.com/chain.pem')
};

EDIT

More Complete Example (Maybe not completely functional)

Server.js

    var fs = require('fs');

    var sessionKey = 'ai_session:';
    var memcachedAuth = require('memcached-auth');

    var clients = {};
    var users = {};

    var options = {
      key: fs.readFileSync('/etc/letsencrypt/live/somesite.com/privkey.pem'),
      cert: fs.readFileSync('/etc/letsencrypt/live/somesite.com/fullchain.pem'),
      ca: fs.readFileSync('/etc/letsencrypt/live/somesite.com/chain.pem')
    };

    var origins = 'https://www.somesite.com:*';
    var https = require('https').createServer(options,function(req,res){

        // Set CORS headers
        res.setHeader('Access-Control-Allow-Origin', origins);
        res.setHeader('Access-Control-Request-Method', '*');
        res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
        res.setHeader('Access-Control-Allow-Headers', '*');

    });

    var io = require('socket.io')(https);
    https.listen(3000);

    io.sockets.on('connection', function(socket){

      socket.on('auth', function(data){

          var session_id = sessionKey+data.token;
          memcachedAuth.is_logged_in(session_id).then( (response) => {

          if(response.is_logged_in){

              // user is logged in
              socket.emit('is_logged_in', true);

              messenger.addUser(socket); 

              // dynamic room
              socket.on('room', function(room){
             socket.join(room);
             console.log('joing room '+room);
              });

              socket.on('message', function(data){
              messenger.receive(data.message_data);                 
              });
          }else{
              // Not logged in
              socket.emit('is_logged_in', false);
          }
          }).catch( (error) => {
          console.log(error);
          });

      });


    });


    var messenger = {
        socket: (socket)=>{
          return socket;  
        },
        subscribe: (room)=>{

        },
        unsubscribe: (room)=>{

        },
        send: (data)=>{

        },
        receive: (data)=>{
        console.log(data);
          //connected
          if (clients[data.user_name]){
            console.log('user');
          }    
        },
        addUser: (socket)=>{
        socket.on('add-user', function(data){
            clients[data] = {
              "socket": socket.id
            };
            console.log('Adding User:' + data);
            console.log(clients);
        });          
        },
        private: (socket)=>{
        // Not working yet...
        socket.on('message', function(data){

            console.log("Sending: " + data + " to " + data.user_name);

            if (clients[data.user_name]){
              io.sockets.connected[clients[data.user_name].socket].emit("response", data);
            } else {
              console.log("User does not exist: " + data.user_name); 
            }
        });           
        },
        disconnect:()=>{
        //Removing the socket on disconnect
        socket.on('disconnect', function() {
         for(var name in clients) {
           if(clients[name].socket === socket.id) {
             delete clients[name];
             break;
           }
         }  
        });         
        }
    }

I have created a repo on github including a more complete version of the above code if anyone is interested: https://github.com/snowballrandom/Memcached-Auth

like image 14
Kyle Coots Avatar answered Oct 19 '22 02:10

Kyle Coots


Was facing the same problem In my case I changed the option parameter of cert to pfx & removed utf8 encoding.

before:

var options = {
    hostname : 'localhost',
    path : '/',
    method : 'POST',
    cert: fs.readFileSync(testCert, 'utf8'),
    passphrase:passphrase,
    agent:false,
    rejectUnauthorized:false
};

after:

var options = {
    hostname : 'localhost',
    path : '/',
    method : 'POST',
    pfx: fs.readFileSync(testCert),
    passphrase:passphrase,
    agent:false,
    rejectUnauthorized:false
};
like image 12
Mayank Kumar Avatar answered Oct 19 '22 02:10

Mayank Kumar