Create a gist now

Instantly share code, notes, and snippets.

@apg /rc4.scm
Created Nov 9, 2012

RC4 (e.g. ARCFOUR) in (Guile) Scheme. Yes, this is vulnerable in many ways, since it's straight up RC4.
;;; RC4, just for the hell of it.
;;; Written for Guile 2.0+
;;; Use like so:
;;; Encypher: (rc4 "Key" (map char->integer (string->list "Plaintext")))
;;; $1 = (187 243 22 232 217 64 175 10 211)
;;; Decypher: (rc4 "Key" $1)
;;; $2 = (80 108 97 105 110 116 101 120 116)
(define (rc4-make-schedule key)
(let ((L (string-length key)))
(let loop ((K (apply vector (map char->integer (string->list key))))
(S (apply vector (iota 256)))
(i 0)
(j 0))
(if (< i 256)
(begin
(set! j (remainder (+ j
(vector-ref S i)
(vector-ref K (remainder i L)))
256))
(let ((t (vector-ref S i)))
(vector-set! S i (vector-ref S j))
(vector-set! S j t)
(loop K S (+ i 1) j)))
S))))
(define (rc4-make-generator S)
(let ((i 0)
(j 0))
(lambda ()
(set! i (remainder (+ i 1) 256))
(set! j (remainder (+ j (vector-ref S i)) 256))
(let ((t (vector-ref S i)))
(vector-set! S i (vector-ref S j))
(vector-set! S j t))
(vector-ref S (remainder
(+ (vector-ref S i) (vector-ref S j))
256)))))
(define (rc4 K P)
(let* ((S (rc4-make-schedule K))
(G (rc4-make-generator S)))
(map (lambda (x)
(logxor (G) x))
P)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment