将小的按位XOR perl函数移植到Ruby

时间:2013-02-19 20:43:07

标签: ruby perl xor

我有以下Perl脚本,它在带有HEX键的字符串上执行按位XOR:

#!/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

1 个答案:

答案 0 :(得分:1)

在perl中,你的代码是uudecodeing输入的字符串,并且在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