1 USING: kernel io strings sequences namespaces math parser
2 vectors hashtables math-contrib crypto ;
5 ! Implemented according to RFC 3174.
20 : get-wth ( n -- wth ) w get nth ; inline
21 : shift-wth ( n -- x ) get-wth 1 bitroll-32 ; inline
23 : initialize-sha1 ( -- )
25 HEX: 67452301 dup h0 set A set
26 HEX: efcdab89 dup h1 set B set
27 HEX: 98badcfe dup h2 set C set
28 HEX: 10325476 dup h3 set D set
29 HEX: c3d2e1f0 dup h4 set E set
31 20 [ HEX: 5a827999 , ] times
32 20 [ HEX: 6ed9eba1 , ] times
33 20 [ HEX: 8f1bbcdc , ] times
34 20 [ HEX: ca62c1d6 , ] times
37 ! W(t) = S^1(W(t-3) XOR W(t-8) XOR W(t-14) XOR W(t-16))
40 over 8 - get-wth bitxor
41 over 14 - get-wth bitxor
42 swap 16 - get-wth bitxor 1 bitroll-32 ;
44 ! f(t;B,C,D) = (B AND C) OR ((NOT B) AND D) ( 0 <= t <= 19)
45 ! f(t;B,C,D) = B XOR C XOR D (20 <= t <= 39)
46 ! f(t;B,C,D) = (B AND C) OR (B AND D) OR (C AND D) (40 <= t <= 59)
47 ! f(t;B,C,D) = B XOR C XOR D (60 <= t <= 79)
48 : sha1-f ( B C D t -- f_tbcd )
52 { [ dup 0 = ] [ drop >r over bitnot r> bitand >r bitand r> bitor ] }
53 { [ dup 1 = ] [ drop bitxor bitxor ] }
54 { [ dup 2 = ] [ drop 2dup bitand >r pick bitand >r bitand r> r> bitor bitor ] }
55 { [ dup 3 = ] [ drop bitxor bitxor ] }
59 #! compute w, steps a-b of RFC 3174, section 6.1
60 16 [ nth-int-be w get push ] each-with
61 16 80 dup <slice> [ sha1-W w get push ] each ;
64 ! step c of RFC 3174, section 6.1
71 : inner-loop ( n -- temp )
72 ! TEMP = S^5(A) + f(t;B,C,D) + E + W(t) + K(t);
74 [ B get C get D get ] keep sha1-f ,
79 ] { } make sum 4294967295 bitand ; inline
81 : set-vars ( temp -- )
82 ! E = D; D = C; C = S^30(B); B = A; A = TEMP;
85 B get 30 bitroll-32 C set
89 : calculate-letters ( -- )
90 ! step d of RFC 3174, section 6.1
91 80 [ inner-loop set-vars ] each ;
94 ! step e of RFC 3174, section 6.1
101 : process-sha1-block ( str -- )
102 80 <vector> w set make-w init-letters calculate-letters update-hs ;
104 : get-sha1 ( -- str )
105 [ [ h0 h1 h2 h3 h4 ] [ get 4 >be % ] each ] "" make ;
107 : (stream>sha1) ( -- )
108 64 read dup length dup bytes-read [ + ] change 64 = [
109 process-sha1-block (stream>sha1)
111 t bytes-read get pad-last-block [ process-sha1-block ] each
116 : stream>sha1 ( stream -- sha1 )
117 [ [ initialize-sha1 (stream>sha1) get-sha1 ] with-stream ] with-scope ;
119 : string>sha1 ( string -- sha1 ) <string-reader> stream>sha1 ;
120 : string>sha1str ( string -- str ) string>sha1 hex-string ;
121 : file>sha1 ( file -- sha1 ) <file-reader> stream>sha1 ;