## Autokey

On the recommendation of my friend Dan, I’m going to try to do some of these programming puzzles from time to time. I’m also going to try work these problems using Perl. Today’s assignment is to make a simple Autokey Cipher, which I accomplished over my lunch break.

use List::Util qw/sum/; if ($#ARGV != 1 ) { print "usage: autokey.pl plainText key\n"; exit; } $plainText = uc $ARGV[0]; $keyBase = uc $ARGV[1]; $key = $keyBase.$plainText; print $key; #$plainText = "ACOLLECTIONOFETUDES"; #$key = "PRAXISACOLLECTIONOF"; $cipherText = ""; sub encipher{ my($thisPlainText, $thisKey) = @_; #Clear Cipher'd text $thisCipherText = ""; #Clear i $i=0; @arrayPlainText = split //, $thisPlainText; @arrayKey = split //, $thisKey; for($i = 0; $i < scalar @arrayPlainText; $i++){ if(@h{@arrayPlainText[$i]} + @h{@arrayKey[$i]} > 27){ $thisCipherText .= @k[@h{@arrayPlainText[$i]} + @h{@arrayKey[$i]} - 27]; #print @h{@arrayPlainText[$i]} + @h{@arrayKey[$i]} - 26 . "\n"; #print @k[@h{@arrayPlainText[$i]} + @h{@arrayKey[$i]} - 26] . "\n"; } else{ $thisCipherText .= @k[@h{@arrayPlainText[$i]} + @h{@arrayKey[$i]} - 1]; #print @h{@arrayPlainText[$i]} + @h{@arrayKey[$i]} . "\n"; #print @k[@h{@arrayPlainText[$i]} + @h{@arrayKey[$i]}] . "\n"; } } return $thisCipherText; } sub decipher{ my($thisCipherText, $thisKey) = @_; @arrayCipherText = split //, $thisCipherText; @arrayKey = split //, $thisKey; for($i = 0; $i < scalar @arrayCipherText; $i++){ if(@h{@arrayCipherText[$i]} - @h{@arrayKey[$i]} < 0){ $thisPlainText .= @k[@h{@arrayCipherText[$i]} - @h{@arrayKey[$i]} + 27]; } else{ $thisPlainText .= @k[@h{@arrayCipherText[$i]} - @h{@arrayKey[$i]} + 1]; } } return $thisPlainText; } @h{'A' .. 'Z'} = (1 .. 26); @k[1 .. 26] = ('A' .. 'Z'); $cipherText = &encipher($plainText, $key); $decipherText = &decipher($cipherText, $key); print " Plain text is: " . $plainText . "\n"; print "Cipher text is: " . $cipherText . "\n"; print "Decipher text is: " . $decipherText . "\n";0