#!/usr/bin/perl # usage: # vigenere.pl -e key inputfile (for encryption of inputfile with key) # vigenere.pl -d key inputfile (for decryption) ($mode, $key, $infile, $optQ) = @ARGV; $quiet = ($optQ eq "-q"); print "Vigenere cipher by nicZ\n" unless ($quiet); &checkForFile($infile); $text = &stripText(`cat $infile`); @inputText = split('', $text); @key = split('', $key); @keyCodes = &encode(@key); $keyLen = scalar(@key); print "Key is $key\n" unless ($quiet); print "\nPlaintext is\n" unless ($quiet); &doEncryption() if ($mode eq "-e"); &doDecryption() if ($mode eq "-d"); sub doEncryption { &blockPrint(@inputText) unless ($quiet); @cipherText = &encrypt(@inputText); print "\nCiphertext is\n" unless ($quiet); &blockPrint(@cipherText); } sub doDecryption { @plainText = &decrypt(@inputText); &blockPrint(@plainText); } sub encrypt { return &crypt(1, @_); } sub decrypt { return &crypt(-1, @_); } sub stripText{ while ($text = shift) { chomp $text; $stext .= $text; } $stext =~ s/( |\.|,|\n)//g; return lc($stext); } sub crypt { my $ende = shift; my @cypher = (); my @codes = &encode(@_); my $lim = scalar(@_); foreach $i (0 .. $lim-1) { push @cypher, ((shift(@codes) + $ende*$keyCodes[$i % $keyLen]) % 26); } return &decode(@cypher); } sub encode { return map(ord($_) - ord('a'), @_); } sub decode { return map(chr($_ + ord('a')), @_); } sub blockPrint { my $i = 0; while ($char = shift) { print " " if ($i % 5 == 0 && $i > 0); print "\n" if ($i % 40 == 0 && $i > 0); print uc($char); $i++; } print "\n"; } sub checkForFile { my ($fn) = @_; die "Error : file $fn does not exist!\n" unless (-e $fn); warn "Warning : file $fn has zero size!\n" if (-z $fn); }