RSS Feed Subscribe to RSS Feed

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";

Tags: , , , ,

Five Years Ago Today...

Leave a Comment

Gravatar: Get your picture displayed next to your comment: http://gravatar.com

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Code: To include code, bracket it with [code language="php"] and [/code].
Example: [code language="php"] echo "Hello, World!"; [/code]

Plugin Help: If your requesting help about a plugin, please provide as much information as possible. At the very least, include your WordPress Version and the Plugin Version!