Skip to content

Instantly share code, notes, and snippets.

@Zibri
Last active August 11, 2019 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zibri/90f5ac6d05c6c1011f5ce501c34891c9 to your computer and use it in GitHub Desktop.
Save Zibri/90f5ac6d05c6c1011f5ce501c34891c9 to your computer and use it in GitHub Desktop.
OTP NodeJS and pure Javascript one-liner
// 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 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)
@Zibri
Copy link
Author

Zibri commented Aug 11, 2019

Any comment?
I don't find this less secure than gauth...
Note: "test_secret" can be also a binary string.

@mbirth
Copy link

mbirth commented Aug 11, 2019

@Zibri
Copy link
Author

Zibri commented Aug 11, 2019

http://motp.sourceforge.net/

What about it? This is just my own implementation. I know there are many, but I find this simpler.

@mbirth
Copy link

mbirth commented Aug 11, 2019

mOTP is very similar. Timestamp + Secret + (Userinput), everything hashed and taking the first $length characters. Just saying.

@Zibri
Copy link
Author

Zibri commented Aug 11, 2019

oh.. I see.. but they are all huge... this is very short.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment