Skip to content

Instantly share code, notes, and snippets.

@Zibri
Last active Aug 11, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@Zibri 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

This comment has been minimized.

Copy link

@mbirth mbirth commented Aug 11, 2019

@Zibri

This comment has been minimized.

Copy link
Owner Author

@Zibri 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

This comment has been minimized.

Copy link

@mbirth mbirth commented Aug 11, 2019

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

@Zibri

This comment has been minimized.

Copy link
Owner Author

@Zibri 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