Skip to content

Commit

Permalink
Merge pull request #9 from khan-asfi-reza/main
Browse files Browse the repository at this point in the history
(feat!): Added salting
  • Loading branch information
theanam authored Nov 20, 2023
2 parents 57663d0 + 3b26ebf commit d5e55e3
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
9 changes: 5 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ const crypto = require("crypto");
function createNewOTP(phone,otp,key="",expiresAfter=5,algorithm="sha256"){
const ttl = expiresAfter * 60 * 1000; //Expires after in Minutes, converteed to miliseconds
const expires = Date.now() + ttl; //timestamp to 5 minutes in the future
const data = `${phone}.${otp}.${expires}`; // phone.otp.expiry_timestamp
const salt = crypto.randomBytes(16).toString('hex'); // Generate a random salt
const data = `${phone}.${otp}.${expires}.${salt}`; // phone.otp.expiry_timestamp.salt
const hashBase = crypto.createHmac(algorithm,key).update(data).digest("hex"); // creating SHA256 hash of the data
const hash = `${hashBase}.${expires}`; // Hash.expires, format to send to the user
const hash = `${hashBase}.${expires}.${salt}`; // Hash.expires.salt, format to send to the user
// you have to implement the function to send SMS yourself. For demo purpose. let's assume it's called sendSMS
return hash;
}
Expand All @@ -39,12 +40,12 @@ function createNewOTP(phone,otp,key="",expiresAfter=5,algorithm="sha256"){
function verifyOTP(phone,otp,hash,key="",algorithm="sha256"){
if(!hash.match(".")) return false; // Hash should have at least one dot
// Seperate Hash value and expires from the hash returned from the user(
let [hashValue,expires] = hash.split(".");
let [hashValue,expires,salt] = hash.split(".");
// Check if expiry time has passed
let now = Date.now();
if(now>expires) return false;
// Calculate new hash with the same key and the same algorithm
let data = `${phone}.${otp}.${expires}`;
let data = `${phone}.${otp}.${expires}.${salt}`;
let newCalculatedHash = crypto.createHmac(algorithm,key).update(data).digest("hex");
// Match the hashes
if(newCalculatedHash === hashValue){
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "otp-without-db",
"version": "1.0.5",
"version": "1.0.6",
"description": "Database less OTP verification with cryptography",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit d5e55e3

Please sign in to comment.