Last active
August 11, 2019 17:47
-
-
Save Zibri/90f5ac6d05c6c1011f5ce501c34891c9 to your computer and use it in GitHub Desktop.
OTP NodeJS and pure Javascript one-liner
This file contains 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
// This code produces a different 6 digits OTP every 30 seconds. | |
// numDigits must be between 1 and 8 | |
otp = await (async (secret,numDigits)=>(Array.prototype.reduce.call(new Uint8Array(await crypto.subtle.digest('SHA-512',new TextEncoder().encode(secret+(Math.floor(new Date().getTime()/30000)).toString(16)))), (a,b,c)=>((((a*257) ^ b) >>> 0) % (10**numDigits)) )).toString().padStart(numDigits,"0")) | |
("test_secret",6) | |
OR | |
Object.defineProperty(window, 'otp', { get: async (secret="test_secret",numDigits=6)=>(Array.prototype.reduce.call(new Uint8Array(await crypto.subtle.digest('SHA-512',new TextEncoder().encode(secret+(Math.floor(new Date().getTime()/30000)).toString(16)))), (a,b,c)=>((((a*257) ^ b) >>> 0) % (10**numDigits)) )).toString().padStart(numDigits,"0") }); | |
Then invoke as: | |
await otp |
This file contains 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
// This code produces a different 6 digits OTP every 30 seconds. | |
// numDigits must be between 1 and 8 | |
otp = ((secret,numDigits)=>{ | |
hash=hash = crypto.createHash('sha512'); | |
hash.update(secret+(Math.floor(new Date().getTime()/30000)).toString(16)); | |
return (Array.prototype.reduce.call(new Uint8Array(hash.digest()),(a,b,c)=>((((a*257) ^ b) >>> 0) % (10**numDigits)) )).toString().padStart(numDigits,"0"); | |
})("test_secret",6) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh.. I see.. but they are all huge... this is very short.