#!/usr/bin/perl # # A perl implementation of the "crypt" program. # # This program implements an rc4 encrytion algorythm # using a variable length key single piece key. # # It takes a file or data stream and encrypts it using the # provided key. Running the output of the program back # through the program with the same key will decrypt it. # # USAGE: rc4 [file name] # If no file name is provided, the script will read from # STDIN. # # Andy Welter # www.the-welters.com # May 2001 # # # Encrypt a buffer at a type. Encryption is a stateful # process, so we use the "@state" global variable to track # the state. sub rc4 { my ($buf) = @_; my ($ebuf, $char); for(unpack('C*',$buf)) { $x++; $y=($state[$x%=256]+$y)%256; @state[$x,$y]=@state[$y,$x]; #&swap; $char= pack (C, $_^=$state[ ($state[$x] + $state[$y]) %256 ]); $ebuf= $ebuf . $char; }; return $ebuf; }; sub prepkey { # # Prepare the encryption key # my @key=@_; my @hexkey=unpack('C*',pack('H*',shift @key)); my ($x, $y); my @t; my @state; # # prepare key for(@t=@state=0..255){ $y=($hexkey[$_%@hexkey]+$state[$x=$_]+$y)%256; @state[$x,$y]=@state[$y,$x]; #&swap; } return @state; }; local @state=prepkey("$ARGV[0]"); my $x=0; my $y=0; my $file; if ( $ARGV[1] eq "" ) { # If no file name was specified, # use standard-in as the file name $file="<&=0"; } else { $file=$ARGV[1]; }; open (IN,"$file") || die "error: can not open $file"; while (read (IN,$buf, 1024)) { print rc4 ($buf); };