Skip to content

Instantly share code, notes, and snippets.

@cooltoast
Last active May 22, 2018 22:16
Show Gist options
  • Save cooltoast/33b3c21e6a97e2efabdfd58c3f4b556d to your computer and use it in GitHub Desktop.
Save cooltoast/33b3c21e6a97e2efabdfd58c3f4b556d to your computer and use it in GitHub Desktop.
// Native JS
function validateSignature(token, url, parameters = {}, files = {}, signature) {
// sort the POST fields first and add them to the url
const paramKeys = Object.keys(parameters).sort();
const paramStr = paramKeys.reduce((acc, paramName) => {
return acc + paramName + parameters[paramName];
}, '');
// sort the files by field name and add their SHA1 sums to the URL
const fileKeys = Object.keys(files).sort();
const fileStr = fileKeys.reduce((acc, fileName) => {
const fileSha1Hash = crypto.createHash('sha1').update(fs.readFileSync(files[fileName])).digest('hex');
return acc + fileName + fileSha1Hash;
}, '');
// timing-safe comparison
return bcrypt.compareSync(signature, crypto.createHmac('sha1', token).update(url + paramStr + fileStr).digest('hex'));
}
// Or with lodash (https://lodash.com)
function validateSignature(token, url, parameters = {}, files = {}, signature) {
// sort the POST fields first and add them to the url
const paramStr = _(parameters)
.toPairs()
.sortBy(_.first)
.map(x => x.join(''))
.join('');
// sort the files by field name and add their SHA1 sums to the URL
const fileStr = _(files)
.mapValues(file => crypto.createHash('sha1').update(fs.readFileSync(file)).digest('hex'))
.toPairs()
.sortBy(_.first)
.map(x => x.join(''))
.join('');
// timing-safe comparison
return bcrypt.compareSync(signature, crypto.createHmac('sha1', token).update(url + paramStr + fileStr).digest('hex'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment