Last active
October 3, 2019 05:27
-
-
Save theanam/4f687fa747114ab6518e96d4c0cdee3c to your computer and use it in GitHub Desktop.
Verify hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// These imports and values are the same from the create source code. Perhaps you should keep them in the same file | |
// For the sake of demonstration, the imports are used here as well. | |
const crypto = require("crypto"); | |
const key = "verysecretkey"; // Key for cryptograpy. Keep it secret | |
function verifyOTP(phone,hash,otp){ | |
// Seperate Hash value and expires from the hash returned from the user | |
let [hashValue,expires] = hash.split("."); | |
// Check if expiry time has passed | |
let now = Date.now(); | |
if(now>parseInt(expires)) return false; | |
// Calculate new hash with the same key and the same algorithm | |
let data = `${phone}.${otp}.${expires}`; | |
let newCalculatedHash = crypto.createHmac("sha256",key).update(data).digest("hex"); | |
// Match the hashes | |
if(newCalculatedHash === hashValue){ | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment