(* RC4 *) (* $Id: rc4.ml,v 1.1 2003/01/12 15:33:00 berke Exp $ *) (* By Berke Durak *) type key_schedule = { mutable s : int array; mutable i : int; mutable j : int; } let schedule_of_key m k = let n = Array.length k in let s = Array.make m 0 in let t = Array.make m 0 in for i = 0 to m - 1 do s.(i) <- i; t.(i) <- k.(i mod n) done; let rec loop i j = if i < m then begin let j = (j + s.(i) + t.(i)) mod m in let t = s.(i) in s.(i) <- s.(j); s.(j) <- t; loop (i + 1) j end else { s = s; i = 0; j = j; } in loop 0 0 let get_byte ks = let m = Array.length ks.s in ks.s.((ks.s.(ks.i) + ks.s.(ks.j)) mod m) let step_forward ks = let m = Array.length ks.s in let i = ks.i and j = ks.j in let i' = (i + 1) mod m in let j' = (j + ks.s.(i')) mod m in let x = ks.s.(i') in ks.s.(i') <- ks.s.(j'); ks.s.(j') <- x; ks.i <- i'; ks.j <- j' let step_backward ks = let m = Array.length ks.s in let i' = ks.i and j' = ks.j in let x = ks.s.(i') in ks.s.(i') <- ks.s.(j'); ks.s.(j') <- x; let i = (i' - 1 + m) mod m in let j = (m + j' - ks.s.(i')) mod m in ks.i <- i; ks.j <- j let key_of_string s = let m = String.length s in let a = Array.make m 0 in for i = 0 to m - 1 do a.(i) <- Char.code s.[i] done; a let test_key = "thisisamoddafokkingtest" (* let _ = let ks = schedule_of_key 256 (key_of_string test_key) in for i = 1 to 10240 do print_char (Char.chr (get_byte ks)) done *)