1

我有以下 Perl 脚本,它使用 HEX 键对字符串进行按位异或:

#!/usr/bin/perl

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

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

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

运行它的示例输出:

$ perl deXOR.pl
Enter string to decode: (?LM-D\=^5DB$ \n
Decoded string value: Bx3k8aaW

我试图将它移植到 Ruby 但我做错了,结果不一样:

#!/usr/bin/env ruby

key = ['3cb37efae7f4f376ebbd76cd'].pack('H*')

print "Enter string to decode: "
STDOUT.flush
a_string = gets
a_string.chomp!
a_string = a_string.gsub(/\//, "")
dec = String(key)
puts "Decoded string value: "+dec

class String
  def xor(key)
    text = dup
    text.length.times {|n| text[n] = (text[n].ord ^ key[n.modulo key.size].ord).chr }
    text
  end
end

样本输出:

$ ruby deXOR.rb
Enter string to decode: (?LM-D\=^5DB$ \n
Decoded string value: <³~úçôóvë½vÍ

我究竟做错了什么?有什么想法吗?谢谢!

变了,还是乱七八糟

key = ['3cb37efae7f4f376ebbd76cd'].pack('H*')

def xor(text, key)
  text.length.times {|n| text[n] = (text[n].ord ^ key[n.modulo key.size].ord).chr}
  text
end

print "Enter string to decode: "
STDOUT.flush
a_string = gets
a_string.chomp!
a_string = a_string.gsub(/\//, "")
dec = xor(a_string, key)
puts "Decoded string value: "+dec

输出:

$ ruby deXOR.rb
Enter string to decode: (?LM-D\=^5DB$ \n
Decoded string value: 2·Ê°¯Kµ2"

在 Digitaka 的帮助下工作的版本:

key = ['3cb37efae7f4f376ebbd76cd'].pack('H*')

def decode(str, key)
  text = str.dup
  text.length.times { |n| text[n] = (text[n].ord ^ key[n.modulo key.size].ord).chr }
  text
end

print "Enter string to decode: "
STDOUT.flush
a_string = gets
a_string.chomp!
a_string = a_string.gsub(/\\n/, "")
a_string = a_string.gsub(/\\/, "")
a_string = a_string.unpack('u')[0]
dec = decode(a_string,key)
puts "Decoded string value: "+dec

输出:

$ ruby deXOR.rb
Enter string to decode: (?LM-D=^5DB$ \n
Decoded string value: Bx3k8aaW
4

1 回答 1

1

在 perl 中,您的代码正在对输入的字符串进行 uudecode,而在 ruby​​ 中没有发生等价的情况。这个片段 uudecodes 和像 perl 代码一样解码:

key = ['3cb37efae7f4f376ebbd76cd'].pack('H*')

# took some liberties to simplify the input text code
istr = "(?LM-D=^5DB$ ".unpack('u')[0]

def decode(str, key)
  text = str.dup
  text.length.times { |n| text[n] = (text[n].ord ^ key[n.modulo key.size].ord).chr }
  text
end

puts decode(istr,key) 
# => Bx3k8aaW
于 2013-02-20T07:42:26.187 回答