1 ! Copyright (C) 2018, 2020, 2022 Alexander Ilin.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: base32 calendar checksums.hmac checksums.sha endian
4 kernel math math.bitwise math.parser namespaces sequences
8 SYMBOLS: totp-hash totp-digits ;
9 totp-hash [ sha1 ] initialize
10 totp-digits [ 6 ] initialize
14 : totp-value ( hash-bytes -- n )
15 [ last 4 bits dup 4 + ] keep <slice> be> 31 clear-bit ;
19 : timestamp>count* ( timestamp secs/count -- count )
20 [ timestamp>unix-time ] dip /i 8 >be ; inline
22 : timestamp>count ( timestamp -- count )
25 : totp* ( count key hash -- n )
26 hmac-bytes totp-value ;
28 : digits ( n digits -- string )
29 [ number>string ] dip [ CHAR: 0 pad-head ] keep tail* ;
31 : totp ( key -- string )
32 dup string? [ CHAR: space swap remove >upper base32> ] when
33 now timestamp>count swap totp-hash get totp* totp-digits get digits ;