Skip to content

Instantly share code, notes, and snippets.

@neonexus
Last active December 21, 2023 03:56
Show Gist options
  • Save neonexus/a6d1acc13c75b35ceba7832e1e6421cb to your computer and use it in GitHub Desktop.
Save neonexus/a6d1acc13c75b35ceba7832e1e6421cb to your computer and use it in GitHub Desktop.
Check with PwnedPasswords.com API
const crypto = require('crypto');
const https = require('https');
/**
* @callback doneCb
* @param {number|string|Error} pwnedCountOrError - Either the pwnedCount of the password, or an error.
*/
/**
* Check with PwnedPasswords.com API.
*
* @param {string} rawPassword - Raw password string. This is NEVER transmitted over the internet.
* @param {doneCb} done - A callback function; will get either a pwnedCount, or an error.
*/
function checkWithPwnedPasswords(rawPassword, done) {
const sha1Hash = crypto.createHash('sha1').update(rawPassword).digest('hex').toUpperCase();
const passwordChunk1 = sha1Hash.substring(0, 5);
const passwordChunk2 = sha1Hash.substring(5);
const options = {
hostname: 'api.pwnedpasswords.com',
path: `/range/${passwordChunk1}`,
method: 'GET',
headers: {
'User-Agent': 'Node.js'
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
const chunks = data.split('\r\n');
const matches = chunks.filter(s => s.includes(passwordChunk2));
if (matches.length) {
const bits = matches[0].split(':');
return done(parseInt(bits[1]));
}
return done(0);
}
return done(`HTTP Status: ${res.statusCode}`);
});
});
req.on('error', (err) => {
console.error(err);
return done(err);
});
req.end();
}
module.exports = checkWithPwnedPasswords;

Check with PwnedPasswords.com API

This little script will take in a raw password string, hash it, then search PwnedPasswords.com API using only the first 5 characters of the password hash.

See: https://haveibeenpwned.com/API/v2#PwnedPasswords

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