#/usr/bin/perl -w
# Demo Version -
# AY2012/2013 ST2614 Assignment
# PM to support Personal Password Manager
package ST2614 ;
our $VERSION = 1.0;
sub getAscii {
# This is a helper function to support encode() and decode()
#
#input a normal string
# convert each char of the string to its corresponding ascii cod
+e
# return the list of the ascii codes
# in one , delimited string
my $plaintext= shift;
my @asciilist = ();
my @tmplist = split('', $plaintext);
foreach $ch (@tmplist) {
push (@asciilist, ord($ch)); # use ord to get ascii code
}
return join(",",@asciilist);
}
sub encode {
# simple xor encoding
# Argument 1 - A string in plain text - to be encoded
# Argument 2 - A string in plain text, represent the key
# return the xor result in ascii form
my ($text , $key) = @_;
$text = getAscii($text);
$key = getAscii($key);
my @textlist = split(',',$text);
my @keyblk = split(',',$key);
my $index = 0;
my $max = @keyblk;
my @encodedlist = ();
foreach $chcode (@textlist) {
# simple xor encoding
# must use int() to force a numeric xor operation
my $secret = int($chcode) ^ int($keyblk[$index]);
push(@encodedlist,$secret); # store the result
# recycle the key block
$index = ($index+1) % $max;
}
return join(",",@encodedlist);
}
sub decode {
# simple xor decoding
# Argument 1 - encoded string in ascii list form
# Argument 2 - A string in plain text, represent the key
# return the xor result in plain text string form
my ($secret , $key) = @_;
$key = getAscii($key);
# break the line into array and xor with the keyblock
my @secretlist = split(',',$secret);
my @keyblk = split(',',$key);
my $index = 0;
my $max = @keyblk;
my $orgText = "";
foreach $chcode (@secretlist) {
my $org = int($chcode) ^ int($keyblk[$index++]);
# convert numeric ascii value back to character form
# and append it to $orgText
$orgText .= chr($org);
$index = $index % $max;
}
return $orgText;
}
1; # required to return 1 at the end of a pm file
|