Advertisement
Anakthewolf

Caesar Cipher script and class

May 11th, 2014
431
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. SCRIPT
  2.  
  3. #!/usr/bin/perl -w
  4.  
  5. use strict;
  6. use warnings;
  7. use feature 'say';
  8. use Switch;
  9.  
  10. use Crypt::CaesarCipher;
  11. my $shiftValue='3';
  12.  
  13. my $plainText;
  14. switch (defined($ARGV[0])) {
  15.     case '' {
  16.         $plainText='workshop at unina mmxiv'
  17.     }
  18.     else {
  19.         $plainText=$ARGV[0]
  20.     }
  21. }
  22.  
  23. say '--> Testo in chiaro: '.$plainText;
  24.  
  25. # istanza oggetto cifrario di Cesare
  26. my $caesarCipher=Crypt::CaesarCipher->new({setShift => $shiftValue});
  27.  
  28. # invocazione metodo di cifratura
  29. my $encrypted=$caesarCipher->encrypt($plainText);
  30. say '--> Messaggio criptato '.$encrypted;
  31.  
  32. # decifrazione del messaggio criptato
  33. my $decrypted=$caesarCipher->decrypt($encrypted);
  34. say '--> Messaggio decriptato '.$decrypted;
  35.  
  36. CLASSE Crypt::CaesarCipher
  37.  
  38. # package Caesar Cipher by anak@cpan.org - CC-BY-SA
  39. package Crypt::CaesarCipher;
  40.  
  41. use strict;
  42. use warnings;
  43. use base 'Class::Accessor';
  44.  
  45. Crypt::CaesarCipher->mk_accessors('encrypt','decrypt','setShift');
  46. our $VERSION='0.01';
  47.  
  48. # ascii a = 97 e ascii z= 122
  49.  
  50. sub encrypt {
  51.     my ($self,$plainText)=@_;
  52.     my $encryptedText;
  53.  
  54.     foreach my $plainChar(split //,$plainText) {
  55.         my $ordCharShifted=ord($plainChar)+$self->setShift;
  56.         if ($ordCharShifted > 122) {
  57.             $encryptedText.=chr($ordCharShifted - 122 + 96)
  58.         } else {
  59.             $encryptedText.=chr($ordCharShifted)
  60.         }
  61.     }
  62.     return $encryptedText
  63. }
  64.  
  65. sub decrypt {
  66.     my ($self,$encryptedText)=@_;
  67.     my $plainText;
  68.  
  69.     foreach my $encryptedChar(split //,$encryptedText) {
  70.         my $ordCharShifted=ord($encryptedChar)-$self->setShift;
  71.         if ($ordCharShifted < 97) {
  72.             $plainText.=chr(122 - $ordCharShifted + 96)
  73.         } else {
  74.             $plainText.=chr($ordCharShifted)
  75.         }
  76.     }
  77.     return $plainText
  78. }
  79. 1;
Advertisement
RAW Paste Data Copied
Advertisement