Skip to content

Instantly share code, notes, and snippets.

@arvindkumarbadwal
Created May 15, 2020 13:58
Show Gist options
  • Save arvindkumarbadwal/0b81f4bc7a22f9be17556f823d7ee8f6 to your computer and use it in GitHub Desktop.
Save arvindkumarbadwal/0b81f4bc7a22f9be17556f823d7ee8f6 to your computer and use it in GitHub Desktop.
Axios SSL Certificate Pinning
const tls = require('tls');
const https = require('https');
const crypto = require('crypto');
const axios = require('axios');
function sha256(s) {
return crypto.createHash('sha256').update(s).digest('base64');
}
const options = {
rejectUnauthorized: true,
checkServerIdentity: function(host, cert) {
// Make sure the certificate is issued to the host we are connected to
const err = tls.checkServerIdentity(host, cert);
if (err) {
return err;
}
// Pin the public key, similar to HPKP pin-sha25 pinning
const pubkey256 = 'ORH27mxcLwxnNpR7e0i6pdDPWLXdpeWgr5bEfFVbxW8=';
if (sha256(cert.pubkey) !== pubkey256) {
return new Error('Certificate verification error');
}
// OR Pin the exact certificate, rather than the pub key
const cert256 = '3A:AE:0A:71:39:2F:86:22:5E:F2:9F:A9:FE:0C:66:BD:' +
'8A:85:AB:F5:C6:8F:F2:D1:E3:33:A8:EF:6F:EB:52:87';
if (cert.fingerprint256 !== cert256) {
return new Error('Certificate verification error');
}
},
};
const agent = new https.Agent(options);
axios.get('https://api.github.com', { httpsAgent: agent })
.then(response => {
console.log('All OK. Server matched our pinned cert or public key')
})
.catch(error => {
console.error(error.message)
});
@tnanhpt
Copy link

tnanhpt commented Sep 17, 2021

Can't call to function checkServerIdentity.

@gkasireddy202
Copy link

Hi Team,

What is cert parameter in the function.How to get cert?.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment