2013-02-20 116 views
0

如何在Perl中执行按位异或时转义“^”字符?我的剧本是好的,但是当我输入像.1M80P]/)[email protected]*>RQF^RM< \n一个字符串,然后输出得到弄糟:包含“^”的Perl XOR转义字符串

#!/usr/bin/perl 

$key = pack("H*","3cb37efae7f4f376ebbd76cd"); 

print "Enter string to decode: "; 
$str=<STDIN>;chomp $str; $str =~s/\\(.)/$1/g; 
$dec = decode($str); 
print "Decoded string value: $dec\n"; 

sub decode{ 
    @[email protected]_; 
    my $sqlstr = $subvar[0]; 
    $cipher = unpack("u", $sqlstr); 
    $plain = $cipher^$key; 
    return substr($plain, 0, length($cipher)); 
} 

输出:

Enter string to decode: .1M80P]/)[email protected]*>RQF^RM< \n 
Decoded string value: zen94==tuvosÊ× 

有什么奇怪的,下面的字符串,\=_\\^M;+ [email protected]\n工程确定并解码为[email protected]!但再次如预期还给[email protected]Æ

这里.;H ^F8B8EQ">SA^BDL8 \n不起作用由池上清洁代码(虽然相同的结果):

#!/usr/bin/perl 
use strict; 
use warnings; 

sub deliteral { 
    my ($s) = @_; 
    $s =~ s/\\n/\n/g; 
    die "Unrecognised escape \\$1\n" if $s =~ /\\[a-zA-Z0-9]/; 
    $s =~ s/\\(.)/$1/sg; 
    return $s; 
} 

sub uudecode { 
    return unpack 'u', $_[0]; 
} 

sub decode { 
    my ($key, $cipher) = @_; 
    return substr($cipher^$key, 0, length($cipher)); # XXX 
} 

my $key = pack('H*', '3cb37efae7f4f376ebbd76cd'); 

print "Enter string to decode: "; 
chomp(my $coded = <STDIN>); 

my $cipher = uudecode(deliteral($coded)); 
my $plain = decode($key, $cipher); 
print("Plain text: $plain\n"); 
+1

您期待的输出是什么? – 2013-02-20 10:58:36

+0

所以你说它在纯文本比关键字长时不起作用。 – ikegami 2013-02-20 12:15:13

+0

不是,这是有效的:',6 \\\ = =/S,G \!PQF?SQF5 \ n'解码为'gt16.50otroX' – bsteo 2013-02-20 12:19:20

回答

0

所以这是解决方案,这要归功于池上帮助:

#!/usr/bin/perl 
use strict; 
use warnings; 

sub deliteral { 
    my ($s) = @_; 
    $s =~ s/\\n/\n/g; 
    die "Unrecognised escape \\$1\n" if $s =~ /(?<!\\)(?:\\{2})*\\([a-zA-Z0-9])/; $s =~ s/\\(.)/$1/sg; 
    return $s; 
} 

sub uudecode { 
    return unpack 'u', $_[0]; 
} 

sub decode { 
    my ($key, $cipher) = @_; 
    return substr($cipher^$key, 0, length($cipher)); # XXX 
} 

my $key = pack('H*', '3cb37efae7f4f376ebbd76cdfce7391e9ed9cee4cfceb4b33332fc96ff7b'); 

print "Enter string to decode: "; 
chomp(my $coded = <STDIN>); 

my $cipher = uudecode(deliteral($coded)); 
my $plain = decode($key, $cipher); 
print("Plain text: $plain\n"); 

的问题是与密钥的长度。