├── .github └── workflows │ └── publish.yml ├── .gitignore ├── index.js ├── package.json ├── readme.MD ├── test.js └── types.d.ts /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to NPM 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | 7 | jobs: 8 | publish-npm: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v1 12 | - uses: actions/setup-node@v1 13 | with: 14 | node-version: 12 15 | registry-url: https://registry.npmjs.org/ 16 | - run: npm publish 17 | env: 18 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theanam/otp-without-db/d5e55e34a232eb523ef20d6f75826a7b99e3d6f1/.gitignore -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * OTP Utility Functions, which has two functions. 3 | * `createNewOTP` is responsible to create a new otp 4 | * `verifyOTP` verifies the generated otp 5 | * @module OTPUtils 6 | */ 7 | const crypto = require("crypto"); 8 | 9 | 10 | /** 11 | * Creates a new OTP (One-Time Password) hash for the given phone number. 12 | * @param {string} phone - The phone number for which OTP is being generated. 13 | * @param {string} otp - The OTP (One-Time Password) to be associated with the phone number. 14 | * @param {string} [key=""] - The secret key used for hashing the OTP data. 15 | * @param {number} [expiresAfter=5] - The number of minutes after which the OTP expires. 16 | * @param {string} [algorithm="sha256"] - The hashing algorithm to be used. 17 | * @returns {string} - The generated OTP hash. 18 | */ 19 | function createNewOTP(phone,otp,key="",expiresAfter=5,algorithm="sha256"){ 20 | const ttl = expiresAfter * 60 * 1000; //Expires after in Minutes, converteed to miliseconds 21 | const expires = Date.now() + ttl; //timestamp to 5 minutes in the future 22 | const salt = crypto.randomBytes(16).toString('hex'); // Generate a random salt 23 | const data = `${phone}.${otp}.${expires}.${salt}`; // phone.otp.expiry_timestamp.salt 24 | const hashBase = crypto.createHmac(algorithm,key).update(data).digest("hex"); // creating SHA256 hash of the data 25 | const hash = `${hashBase}.${expires}.${salt}`; // Hash.expires.salt, format to send to the user 26 | // you have to implement the function to send SMS yourself. For demo purpose. let's assume it's called sendSMS 27 | return hash; 28 | } 29 | 30 | 31 | /** 32 | * Verifies the OTP (One-Time Password) hash for the given phone number and OTP value. 33 | * @param {string} phone - The phone number for which OTP is being verified. 34 | * @param {string} otp - The OTP (One-Time Password) to be verified. 35 | * @param {string} hash - The OTP hash received from the user. 36 | * @param {string} [key=""] - The secret key used for hashing the OTP data. 37 | * @param {string} [algorithm="sha256"] - The hashing algorithm to be used. 38 | * @returns {boolean} - Whether the OTP is verified or not. 39 | */ 40 | function verifyOTP(phone,otp,hash,key="",algorithm="sha256"){ 41 | if(!hash.match(".")) return false; // Hash should have at least one dot 42 | // Seperate Hash value and expires from the hash returned from the user( 43 | let [hashValue,expires,salt] = hash.split("."); 44 | // Check if expiry time has passed 45 | let now = Date.now(); 46 | if(now>expires) return false; 47 | // Calculate new hash with the same key and the same algorithm 48 | let data = `${phone}.${otp}.${expires}.${salt}`; 49 | let newCalculatedHash = crypto.createHmac(algorithm,key).update(data).digest("hex"); 50 | // Match the hashes 51 | if(newCalculatedHash === hashValue){ 52 | return true; 53 | } 54 | return false; 55 | } 56 | 57 | module.exports = { 58 | createNewOTP, 59 | verifyOTP 60 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "otp-without-db", 3 | "version": "1.0.6", 4 | "description": "Database less OTP verification with cryptography", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node test.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git://git@github.com/theanam/otp-without-db.git" 12 | }, 13 | "keywords": [ 14 | "otp", 15 | "sms", 16 | "verification", 17 | "cryptography", 18 | "smsverify", 19 | "emailverify", 20 | "2fa" 21 | ], 22 | "author": { 23 | "name": "Anam Ahmed", 24 | "email": "me@anam.co" 25 | }, 26 | "license": "MIT", 27 | "bugs": { 28 | "url": "https://github.com/theanam/otp-without-db/issues" 29 | }, 30 | "homepage": "https://github.com/theanam/otp-without-db#readme" 31 | } 32 | -------------------------------------------------------------------------------- /readme.MD: -------------------------------------------------------------------------------- 1 | ## OTP verification using Cryptography and without any Database 2 | 3 | #### Background 4 | 5 | This module is derived from my blog post on the technique. You can read the [blog post here](https://blog.anam.co/otp-verification-without-using-a-database/) to understand the technique and motivation. 6 | 7 | #### Dependencies: 8 | 9 | This module depends on the [Crypto](https://nodejs.org/api/crypto.html) built in module on nodeJS. This is the only dependency and should work in any system that has crypto support (Which is technocally majority of the systems at this moment) 10 | 11 | This module also uses some modern JavaScript features like Template literals, Default arguments and modern object literal. This might be a problem if you are planning to use it with older versions of nodeJS 12 | 13 | #### Installation 14 | 15 | You can use npm to install the package with the following code 16 | 17 | npm install --save otp-without-db 18 | 19 | #### Usage 20 | 21 | You need additional tool to create OTP, and send SMS. This module only takes care of the verification part. 22 | 23 | You can take a look at the [otp-generator](https://www.npmjs.com/package/otp-generator) module to create OTP for your users. 24 | 25 | #### Verification process 26 | 27 | OTP verification is done in the following steps: 28 | 29 | 1. A hash is created with the phone number/email address and then sent to the user. 30 | 31 | 2. The user also receives the OTP via SMS, email or any other method. 32 | 33 | 3. The user sends back the hash, OTP and phone/email used in the first request. 34 | 35 | 4. The server verifies the information and returns true if they match. 36 | 37 | Here's a diagram that shows the whole process: 38 | 39 | ![OTP Verification process](https://blog.anam.co/content/images/2019/10/Untitled-Diagram.jpg) 40 | 41 | #### Generating OTP Hash 42 | 43 | We will use the [otp-generator](https://www.npmjs.com/package/otp-generator) tool mentioned previously to create OTP. You can use any other tool or technique. 44 | 45 | const otpGen = require("otp-generator"); 46 | const otpTool = require("otp-without-db"); 47 | const key = "secretKey"; // Use unique key and keep it secret 48 | 49 | let phone = "88017009090"; 50 | let otp = otpGen.generate(6, { upperCase: false, specialChars: false, alphabets: false }); 51 | 52 | let hash = otpTool.createNewOTP(phone,otp,key); 53 | 54 | You can then send this hash to the user as response. The generate method takes these following arguments (In particular order), 55 | 56 | createNewOTP(phoneOrEmail,otp,key="",expiresAfter=5,algorithm="sha256") 57 | 58 | | Argument | Required | default | Description | 59 | | ------------- | -------- | ------- | -------------- | 60 | | phoneOrEmail | true | N/A | Phone or email | 61 | | otp | true | N/A | OTP | 62 | | key | false | "" | unique and secret key for HMAC see: [createHmac](https://nodejs.org/api/crypto.html#crypto_crypto_createhmac_algorithm_key_options)| 63 | | expiresAfter | false | 5 | Expirty in minutes| 64 | | algorithm | false | `sha256`| Algorithm used for hashing the data. Any supported algorithm from OpenSSL| 65 | 66 | 67 | #### Verifying OTP hash 68 | 69 | The user should get the hash from the HTTP request and should get the real OTP via SMS or email. 70 | 71 | Then when the user sends back the information, they can be verified with the following code: 72 | 73 | otpTool.verifyOTP(phone,otp,hash,key); 74 | 75 | This method returns a **Boolean**. If the verification is successful, it will return true. 76 | 77 | This method also takes the following arguments in particular order: 78 | 79 | verifyOTP(phone,otp,hash,key="",algorithm="sha256") 80 | 81 | 82 | | Argument | Required | default | Description | 83 | | ------------- | -------- | ------- | -------------- | 84 | | phoneOrEmail | true | N/A | Phone or email | 85 | | otp | true | N/A | OTP | 86 | | hash | true | N/A | The hash that was returned from the user | 87 | | key | false | "" | unique and secret key for HMAC see: [createHmac](https://nodejs.org/api/crypto.html#crypto_crypto_createhmac_algorithm_key_options)| 88 | | algorithm | false | `sha256`| Algorithm used for hashing the data. Any supported algorithm from OpenSSL| 89 | 90 | 91 | ****** 92 | 93 | This product is created with 🖤 by [Anam Ahmed](https://anam.co), Any improvements and PR is welcome. 94 | 95 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | const otpTool = require("./index"); 2 | 3 | const phone = "8801711223344"; 4 | const key = "verysecret"; 5 | const otp = 1234; 6 | 7 | 8 | 9 | let hash = otpTool.createNewOTP(phone,otp,key); 10 | let verified = otpTool.verifyOTP(phone,otp,hash,key); 11 | 12 | console.log(`Your verification status is ${verified}`); 13 | -------------------------------------------------------------------------------- /types.d.ts: -------------------------------------------------------------------------------- 1 | declare module "OTPModule" { 2 | function createNewOTP( 3 | phone: string, 4 | otp: string, 5 | key?: string, 6 | expiresAfter?: number, 7 | algorithm?: string 8 | ): string; 9 | 10 | function verifyOTP( 11 | phone: string, 12 | otp: string, 13 | hash: string, 14 | key?: string, 15 | algorithm?: string 16 | ): boolean; 17 | 18 | export { createNewOTP, verifyOTP }; 19 | } --------------------------------------------------------------------------------