Skip to content

Instantly share code, notes, and snippets.

@ccheney
Created October 26, 2017 15:51
Show Gist options
  • Save ccheney/479f776675e0b010120d24ff1f67ad9a to your computer and use it in GitHub Desktop.
Save ccheney/479f776675e0b010120d24ff1f67ad9a to your computer and use it in GitHub Desktop.
generate hash+timestamp string & validate hash+timestamp string from userland
/**
* generate hash+timestamp string
* validate hash+timestamp string from userland
*/
const crypto = require('crypto');
const SECRET = ' ';
function _generateHash(isoDateString) {
return crypto
.createHmac('sha256', SECRET)
.update(isoDateString)
.digest('base64');
}
function _validateSignature(hash, isoDateString) {
const hashFromInput = _generateHash(isoDateString);
return hashFromInput === hash;
}
function generateHashTimestampString() {
const isoDateString = new Date().toISOString();
const hash = _generateHash(isoDateString);
return `${hash} ${isoDateString}`;
}
function validateHashTimestampString(hashTimestampString) {
const [hash, isoDateString] = hashTimestampString.split(' ');
return _validateSignature(hash, isoDateString);
}
// const hashTimestampString = generateHashTimestampString();
// const isValid = validateHashTimestampString(hashTimestampString);
// example usage
const isValid = validateHashTimestampString('hmnm5OHx3tTcBaZPnse2mShNJSqOCxoUIr1RBZlGPMY= 2017-10-26T15:43:25.798Z');
if (!isValid) {
throw new Error('Hash mismatch.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment