RC4 in 3 lines of perl


#!/usr/local/bin/perl -0777-- -export-a-crypto-system-sig -RC4-3-lines-PERL
@k=unpack('C*',pack('H*',shift));for(@t=@s=0..255){$y=($k[$_%@k]+$s[$x=$_
]+$y)%256;&S;}$x=$y=0;for(unpack('C*',<>)){$x++;$y=($s[$x%=256]+$y)%256;
&S;print pack(C,$_^=$s[($s[$x]+$s[$y])%256]);}sub S{@s[$x,$y]=@s[$y,$x];}

Malcolm Beattie contributed a 26 byte saving, which combined with losing the usage string allowed the move to 3 lines!

John Allen contributed a further 9 byte saving. Plus a bug fix. He also contributed some perl5 specific improvements (a smallest perl5 version, and a fastest perl5 version).

Legal status

RC4 is a symmetric stream cipher designed by RSADSI. This cipher used to be trade secret of RSADSI, but some anonymous person distributed the source code on the internet last year. It is not known whether the code was "leaked" by a source license holder or whether someone reverse engineered one of the libraries which used RC4. In either case now that it is no longer a trade secret you can use it legally without paying RSA. Using RC4 in a commercial product without buying a license from RSADSI, whilst technically legal, would be impolite, and it is possible that RSADSI may take it upon themselves to reward you with a court case. If they do this it may turn out to be cheaper to buy a license than fight a protracted legal battle.

The cipher

RC4 is a symmetric stream cipher and is fairly fast. It allows keys up to 2048 bits in length. It uses an internal table of 256 bytes which is seeded with your key, so you can use smaller key sizes too. Since the source has been available cryptographers have been studying the RC4 cipher with interest.

Using the perl implementation of RC4

To use you just give a key in hex on the command line and the rc4 perl program will encrypt standard input to standard output. In this example we encrypt the message "test message" with the 32 bit hex key "12abcdef" (such a small key size is insecure, you would choose much larger keys, 128 bits or more for reasonable security). The message is encrypted from stdin to stdout which is redirected to the file "test.rc4":
% echo test message | rc4 12abcdef > test.rc4
To decrypt the message you just reverse the process giving the same key and using the encrypted file:
% rc4 12abcdef < test.rc4

The equivalent C code

The equivalent C code is included here to allow you to test the perl version - they behave in exactly the same way, but the C code is faster, has a lot more lines and is more readable. Here is the equivalent source code plus the testing harness which makes it comparable to perl-RC4:

Equivalent C source code

The source is also available from numerous ftp sites, I got mine from here:

ftp://ftp.ox.ac.uk/pub/crypto/misc/rc4.tar.gz


Comments, html bugs to me (Adam Back) at <aba@dcs.ex.ac.uk>