***** infoCopter.com/perl *****

RC4 Encryption Decryption



Encryption

#!/usr/bin/perl
use Crypt::RC4;

$passphrase = pack('C*', (0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef));

$filein = shift;

$/=undef;

open(FH,"<$filein") or die $!;
$file = (<FH>);
close FH;

$encrypted = RC4( $passphrase, $file );

open (FH,">$filein.rc4") or die $!;
print FH $encrypted;
close FH;

exit (0);

Decryption

#!/usr/bin/perl
use Crypt::RC4;

$passphrase = pack('C*', (0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef));

$filein = shift;

$/=undef;
open(FH,"<$filein") or die $!;
$file = (<FH>);
close FH;

$decrypted = RC4( $passphrase, $file );

open (FH,">$filein.decrypted") or die $!;
print FH $decrypted;
close FH;

exit (0);

Usage

./enc.pl input
cat input.rc4

./dec.pl input.rc4
cat input.rc4.decrypted


Reto's Example (String Only Version)

Encryption

#!/usr/bin/perl
use Crypt::RC4;

$input = $ARGV[0];
$passphrase = $ARGV[1];

$encrypted = RC4( $passphrase, $input );

my $hex = &iso2hex($encrypted);

print '<- ', $hex, " (hex of encrypted string)\n";

sub iso2hex($) {
        my $hex = '';
        for (my $i = 0; $i < length($_[0]); $i++) {
                my $ordno = ord substr($_[0], $i, 1);
                my $hx = sprintf("%lx ", $ordno);
                   $hx = "0$hx" if length($hx) < 3;
                $hex .= $hx;
        }

        $hex =~ s/ $//;
        $hex;
}

Decryption

#!/usr/bin/perl
use Crypt::RC4;

$input = $ARGV[0]; chomp $input;
$passphrase = $ARGV[1]; chomp $passphrase;

my $decrypted = RC4( $passphrase, &hex2iso($input) );

print '<-- ', $decrypted, "\n";

sub hex2iso ($) {
  my $iso = '';
  (my $hex = $_[0]) =~ tr/ //d;
  for (my $i = 0; $i < length($hex); $i += 2) {
     my $char = pack('H8', substr($hex, $i, 2));
     $iso .= substr($char, 0, 1);
  }
  $iso;
}

Usage

$ ./enc.pl "Hello, RC4 World" mysecret
<- de 7f 35 e6 52 d8 34 ef 20 da 6b 9a 24 a8 87 84 (hex of encrypted string)
]$ ./dec.pl "de 7f 35 e6 52 d8 34 ef 20 da 6b 9a 24 a8 87 84" mysecret
<-- Hello, RC4 World
© reto :)