2013-02-19 39 views
1

我有以下的Perl腳本進行按位異或在一根繩子上用六角鍵:港口小按位異或perl的功能,以紅寶石

#!/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 
    @[email protected]_; 
    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 
+0

在你的代碼片段,你不要顯得呼喚你的XOR功能在所有 – 2013-02-19 20:57:03

+0

似乎沒有人能幫助,謝謝反正... – bsteo 2013-02-20 07:09:55

回答

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 
+0

就像一個魅力!謝謝! – bsteo 2013-02-20 08:27:34

+0

嗯,這個編碼的字符串失敗:「*%XI'R-7 \!QT /?_ 0 \ n」 - >「+992ôkä」應該給「+ 99225454 @」 – bsteo 2013-02-20 10:16:26

+0

我想我必須添加「a_string = a_string。 gsub(/ \\ /,「」)「 – bsteo 2013-02-20 10:24:14