Skip to content

Instantly share code, notes, and snippets.

@tracker1
Last active April 2, 2019 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tracker1/9d6ef79941ccaf89286bd01c3ff10d6e to your computer and use it in GitHub Desktop.
Save tracker1/9d6ef79941ccaf89286bd01c3ff10d6e to your computer and use it in GitHub Desktop.
Check haveibeenpwned with JS
import crypto from 'crypto';
import fetch from 'node-fetch';
const PREFIX_LENGTH = 5;
export function hash(passphrase) {
const shaSum = crypto.createHash('sha1');
shaSum.update(String(passphrase).normalize('NFKC'));
return shaSum.digest('hex');
}
export async function passwordBreached(
passphrase,
passcheckUrl = 'https://api.pwnedpasswords.com/range/'
) {
const hashedPass = hash(passphrase);
const hashedPrefix = hashedPass.substr(0, PREFIX_LENGTH);
const hashedPasswordSub = hashedPass.substr(PREFIX_LENGTH);
const response = await fetch(`${passcheckUrl}${hashedPrefix}`, {
method: 'GET',
headers: {
'User-Agent': 'YOURAPP (APP DETAIL; APP_URL) <CONTACT_EMAIL>',
},
});
if (!response.ok)
throw Object.assign(new Error('Unexpected result from passcheck api.'), { response });
const result = await response.text();
return (
result
.split('\n')
.map(line => line.split(':'))
.filter(([suffix]) => hashedPasswordSuffix === suffix.toLowerCase())
.map(([_, count]) => Number(count))
.shift() || 0
);
}
export default passwordBreached;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment