]> gitweb.factorcode.org Git - factor.git/blob - extra/totp/totp.factor
totp: ignore spaces in the key string
[factor.git] / extra / totp / totp.factor
1 ! Copyright (C) 2018, 2020 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
5 strings unicode ;
6 IN: totp
7
8 SYMBOLS: totp-hash totp-digits ;
9 totp-hash [ sha1 ] initialize
10 totp-digits [ 6 ] initialize
11
12 <PRIVATE
13
14 : totp-value ( hash-bytes -- n )
15     [ last 4 bits dup 4 + ] keep <slice> be> 31 clear-bit ;
16
17 PRIVATE>
18
19 : timestamp>count* ( timestamp secs/count -- count )
20     [ timestamp>unix-time ] dip /i 8 >be ; inline
21
22 : timestamp>count ( timestamp -- count )
23     30 timestamp>count* ;
24
25 : totp* ( count key hash -- n )
26     hmac-bytes totp-value ;
27
28 : digits ( n digits -- string )
29     [ number>string ] dip [ CHAR: 0 pad-head ] keep tail* ;
30
31 : totp ( key -- string )
32     dup string? [ [ CHAR: space = ] reject >upper base32> ] when
33     now timestamp>count swap totp-hash get totp* totp-digits get digits ;