Time-based one-time password algorithm: Difference between revisions
Content added Content deleted
m (→{{header|zkl}}: comment) |
(→{{header|zkl}}: Added example with multiple outputs) |
||
Line 520: | Line 520: | ||
} // OneTimePassword</lang> |
} // OneTimePassword</lang> |
||
Note: MsgHash hashes return a string by default, they can also return the hash as bytes. Ditto the HMAC routines, it is the third parameter. So, to create a hmac that returns bytes, use (eg) MsgHash.extra.hmacSHA1.fp2(False), this creates a partial application (closure) of the hmac using SHA-1 fixing the third parameter as False. |
Note: MsgHash hashes return a string by default, they can also return the hash as bytes. Ditto the HMAC routines, it is the third parameter. So, to create a hmac that returns bytes, use (eg) MsgHash.extra.hmacSHA1.fp2(False), this creates a partial application (closure) of the hmac using SHA-1 fixing the third parameter as False. |
||
{{out|Example |
{{out|Example uses}} |
||
<lang zkl>fcn example_simple{ |
<lang zkl>fcn example_simple{ |
||
// Simple 6-digit HOTP code: |
// Simple 6-digit HOTP code: |
||
Line 547: | Line 547: | ||
println(code) //-->eg 707355416 |
println(code) //-->eg 707355416 |
||
}();</lang> |
}();</lang> |
||
{{out|Example use}} |
|||
Showing how to sync with changes over time. A six digit OTP w/MD5 changing every 17 seconds. Latency can effect the result when totp is called at a time boundary, so a retry may be required. |
|||
<lang zkl>fcn overTime{ |
|||
secret,ts:= "SOME_SECRET",17; |
|||
otp := OneTimePassword(6,ts,Time.Clock.time(),MsgHash.extra.hmacMD5.fp2(False)); |
|||
chg,s := 0,""; |
|||
while(1){ |
|||
code,t := otp.totp(secret),Time.Clock.time() - otp.baseTime; |
|||
if(t/ts!=chg){ chg = t/ts; s=" (should change)"; } |
|||
println("%4d: %6d %s".fmt(t,code,s)); s = ""; |
|||
Atomic.sleep(10); |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
0: 53454 |
|||
10: 53454 |
|||
20: 2947 (should change) |
|||
30: 2947 |
|||
40: 287972 (should change) |
|||
50: 287972 |
|||
... |
|||
220: 510180 |
|||
230: 207 (should change) |
|||
240: 380959 (should change) |
|||
250: 380959 |
|||
</pre> |
|||
{{out|HMAC code}} |
|||
The MsgHash HMAC routines are pretty simple (the hash code is C), included here for completeness: |
The MsgHash HMAC routines are pretty simple (the hash code is C), included here for completeness: |
||
<lang zkl>// https://en.wikipedia.org/wiki/Hash-based_message_authentication_code |
<lang zkl>// https://en.wikipedia.org/wiki/Hash-based_message_authentication_code |