Perl中的程序加密很好,但解密完全出现在0。为什么会这样?我使用相同的方法来加密/解密字符串。
$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;
}
答案 0 :(得分:1)
您的变量$pacstr
是要编码的字符串的一部分,其长度等于或小于密钥的长度。
此处,您的密钥为948D5E5
,长度为七个字符,因此$pacstr
的第一个值是$string
的前七个字符,即This is
。< / p>
所以你的陈述
$pac = hex($pacstr)
正在做
$pax = hex('This is')
返回零,因为字符串中没有有效的十六进制数字。
当然,您必须在每个 Perl程序的开头遇到use strict
和use warnings
的劝诫?如果你在这里遵循了这个建议,你会看到以下
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.
这是该问题的大线索。