Request with X509 Certificate


I have received a X509 certificate (one .cer file), I can decode it, so no problems on that. Now I want to sign a request with this certificate in node, but I can't get this to work:

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

var options = {
    host: '',
    path: '/my-subscription-id/services/hostedservices',
    port: 443,
    method: 'GET',
    cert: fs.readFileSync("./SSLDevCert.cer"),
    agent: false

var req = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    res.on('data', function(d) {

This fails with

Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Object.createCredentials (crypto.js:72:31)
at Object.connect (tls.js:857:27)
at Agent._getConnection (https.js:61:15)
at Agent._establishNewConnection (http.js:1183:21)

Doing the same in C# works fine:

var req = (HttpWebRequest)WebRequest.Create(string.Format("{0}/services/hostedservices", "my-subscription-id"));
req.ClientCertificates.Add(new X509Certificate2(File.ReadAllBytes("./SSLDevCert.cer"));
var resp = req.GetResponse();
Problem courtesy of: Jan Jongboom


A follow up on this:

Only .cer file probably means that the private key is in the certificate (well that's the case with the Azure certs), you will have to transform in a PEM file (that starts with ----BEGIN RSA PRIVATE KEY----) and then do a request with:

var key = fs.readFileSync("./key.pem");
var options = {
    cert: key,
    key: key

Getting the private key from the file can be a bit tricky, but this worked on Azure certificates, so it might help any of you:

openssl pkcs12 -in ' + file + ' -nodes -passin pass:

(note the empty pass argument)

Solution courtesy of: Jan Jongboom


PEM_read_bio expects certificate in PEM format, while you have certificate in "raw" DER format. Obviously you need to convert your certificate to PEM format.

BTW .cer files in DER format don't contain private key and can't be used for signing anything.

You need to re-check what you actually have in your .cer file and in what format.

Discussion courtesy of: Eugene Mayevski 'Allied Bits

This recipe can be found in it's original form on Stack Over Flow.