RC4 in 4 lines of perl

#!/usr/local/bin/perl -- -export-a-crypto-system-sig -RC4-in-4-lines-of-PERL
(@k=unpack('C*',pack('H*',$ARGV[0])))||die"$0 key <in >out\n";for(@t=0..255)
=$y=0;sub S{($s[$x],$s[$y])=($s[$y],$s[$x]);}for(unpack('C*',<STDIN>)){$x++;
$x%=256;$y=($s[$x]+$y)%256;&S;print pack('C',$_^=$s[($s[$x]+$s[$y])%256]);}

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: