【问题标题】:Port small bitwise XOR perl function to Ruby将小的按位 XOR perl 函数移植到 Ruby
【发布时间】:2017-06-07 04:13:01
【问题描述】:

我有以下 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

【问题讨论】:

  • 在你的 sn-p 中你似乎根本没有调用你的 xor 函数
  • 好像没人能帮忙,还是谢谢...

标签: ruby perl xor


【解决方案1】:

在 perl 中,您的代码正在对输入的字符串进行 uudecode,而在 ruby​​ 中没有发生等价的情况。这个 sn-p uudecode 和 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

【讨论】:

  • 像魅力一样工作!谢谢!
  • 嗯,这个编码字符串失败了:"*%XI'R-7\!QT/?_0 \n" -> "+992ôkäÂ" 应该给出 "+99225454@"
  • 我想我必须添加 "a_string = a_string.gsub(/\\/, "")"
  • 是的,很抱歉,这是我为了得到工作的 sn-p 而抽出的东西之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2019-07-09
相关资源
最近更新 更多