home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / RC4.pm < prev    next >
Encoding:
Perl POD Document  |  2001-05-04  |  1.9 KB  |  94 lines

  1. # $Id: RC4.pm,v 1.5 2001/05/04 08:58:22 btrott Exp $
  2.  
  3. package Net::SSH::Perl::Cipher::RC4;
  4.  
  5. use strict;
  6.  
  7. use Net::SSH::Perl::Cipher;
  8. use base qw( Net::SSH::Perl::Cipher );
  9.  
  10. sub new {
  11.     my $class = shift;
  12.     my $ciph = bless { }, $class;
  13.     $ciph->init(@_) if @_;
  14.     $ciph;
  15. }
  16.  
  17. sub init {
  18.     my $ciph = shift;
  19.     my($key, $iv) = @_;
  20.     $ciph->{key} = substr($key, 0, $ciph->keysize);
  21.  
  22.     $key = substr($key, 0, $ciph->keysize);
  23.     my @k = unpack 'C*', $key;
  24.     my @s = 0..255;
  25.     my($y) = (0);
  26.     for my $x (0..255) {
  27.         $y = ($k[$x % @k] + $s[$x] + $y) % 256;
  28.         @s[$x, $y] = @s[$y, $x];
  29.     }
  30.     $ciph->{s} = \@s;
  31.     $ciph->{x} = 0;
  32.     $ciph->{y} = 0;
  33. }
  34.  
  35. sub blocksize { 8 }
  36. sub keysize { 16 }
  37.  
  38. sub encrypt {
  39.     my($ciph, $text) = @_;
  40.     $text = RC4($ciph, $text);
  41.     $text;
  42. }
  43.  
  44. sub decrypt {
  45.     my($ciph, $text) = @_;
  46.     $text = RC4($ciph, $text);
  47.     $text;
  48. }
  49.  
  50. sub RC4 {
  51.     my($ciph, $text) = @_;
  52.     my($x, $y, $trans) = ($ciph->{x}, $ciph->{y}, '');
  53.     my $s = $ciph->{s};
  54.     for my $c (unpack 'C*', $text) {
  55.         $x = ($x + 1) % 256;
  56.         $y = ( $s->[$x] + $y ) % 256;
  57.         @$s[$x, $y] = @$s[$y, $x];
  58.         $trans .= pack('C', $c ^= $s->[( $s->[$x] + $s->[$y] ) % 256]);
  59.     }
  60.     $ciph->{x} = $x;
  61.     $ciph->{y} = $y;
  62.     $trans;
  63. }
  64.  
  65. 1;
  66. __END__
  67.  
  68. =head1 NAME
  69.  
  70. Net::SSH::Perl::Cipher::RC4 - RC4 encryption/decryption
  71.  
  72. =head1 SYNOPSIS
  73.  
  74.     use Net::SSH::Perl::Cipher;
  75.     my $cipher = Net::SSH::Perl::Cipher->new('RC4', $key);
  76.     print $cipher->encrypt($plaintext);
  77.  
  78. =head1 DESCRIPTION
  79.  
  80. I<Net::SSH::Perl::Cipher::RC4> provides RC4 (I<arcfour>)
  81. encryption support for the SSH2 protocol implementation in
  82. I<Net::SSH::Perl>. Unlike the other I<Net::SSH::Perl::Cipher>
  83. objects, the I<RC4> module relies on no outside libraries;
  84. the RC4 algorithm is implemented entirely in this module.
  85.  
  86. RC4 uses key sizes of 16 bytes.
  87.  
  88. =head1 AUTHOR & COPYRIGHTS
  89.  
  90. Please see the Net::SSH::Perl manpage for author, copyright,
  91. and license information.
  92.  
  93. =cut
  94.