\ arcfour 05.1.22 NAB

needs core-ext

decimal

module arcfour

: carray ( n "name" -- )
  create  chars allot
  does> ( n -- addr )  swap chars + ;

256 carray S
0 value j

: j+! ( n -- )  j +  255 and  to j ;

: init-S ( -- )  256 0 do  i dup S c!  loop ;

: mix-S ( K-addr length -- )
  256 0 do
\ j=j+S[i]+K[i modulo length]
    2dup  i swap mod chars +  c@
    i S c@  +  j+!
\ swap S[i] and S[j]
    j S c@  i S c@  j S c!  i S c!
  loop  2drop ;

public:

: arcfourkey ( K-addr length -- )
  init-S  0 to j  mix-S ;

: arcfour ( M-addr length -- )
  0 to j
  swap 1- swap
  1+ 1 do
\ j=j+S[i]
    i S c@ j+!
\ swap S[i] and S[j]
    j S c@  i S c@  2dup  j S c!  i S c!
\ xor M[i-1] with S[j]+S[i]
    + 255 and S  c@  over i chars +  dup
    c@ rot xor  swap c!
  loop  drop ;

private:

create MD5digest 16 chars allot

public:

: MD5 ( c-addr u -- c-addr2 16 )
  MD5digest >abs  2swap  swap >abs
  EncDigestMD5 drop
  MD5digest 16 ;

end-module
