Reputation: 7
The program in Perl encrypts fine but decryption is coming out all 0's. Why is this happening? I used the same method to encrypt/decrypt the string.
$string = "This is an encryption program"; # any length
$keystr = "948D5E5"; # length <= 8
print "original : ", $string, "\n";
$enc = hexcrypt($string, $keystr);
print "encrypted : ", $enc, "\n";
$dec = hexcrypt($enc, $keystr);
print "decrypted : ", $dec, "\n";
sub hexcrypt {
my (@pac, $pacstr, $l, $pac, $pacenc, $format, $pacencstr);
my @string = split(//, @_[0]); # the string to encrypt
my $keystr = @_[1]; # the key
my $key = hex($keystr); # the key in binary
my $keylength = length($keystr);
my $encstr = ""; # accumulator for returned string
do {
@pac = splice(@string, 0, $keylength); # take out a packet of digits (or less at end)
$pacstr = join("", @pac); # into a string
$l = length($pacstr);
$pac = hex($pacstr); # convert to a 32-bit integer
$pacenc = $pac ^ ($key >> ($keylength * 4 - 4 * $l)); # shift key right if $l < $keylength, and XOR
$format = "%0" . sprintf("%.d", $l) . "X"; # we want the leading zeros
$pacencstr = sprintf($format, $pacenc); # back into a string
$encstr .= $pacencstr; # add to encrypted string
} while scalar @string > 0;
return $encstr;
}
Upvotes: 0
Views: 96
Reputation: 126732
Your variable $pacstr
is a chunk of the string to be encoded, with a length equal to or less than the length of the key.
Here, your key is 948D5E5
which is seven characters long, so the first value of $pacstr
is the first seven characters of $string
, which is This is
.
So your statement
$pac = hex($pacstr)
is doing
$pax = hex('This is')
which returns zero because there are no valid hex digits in the string.
Surely you must have come across exhortations to use strict
and use warnings
at the start of every Perl program? If you had followed this advice here you would have seen the following
Illegal hexadecimal digit 'T' ignored at E:\Perl\source\xmls.pl line 33.
Illegal hexadecimal digit ' ' ignored at E:\Perl\source\xmls.pl line 33.
Illegal hexadecimal digit 'r' ignored at E:\Perl\source\xmls.pl line 33.
Illegal hexadecimal digit ' ' ignored at E:\Perl\source\xmls.pl line 33.
Illegal hexadecimal digit 'm' ignored at E:\Perl\source\xmls.pl line 33.
which is a big clue to the problem.
Upvotes: 1