问题描述
显然,这用来在红宝石1.8.7工作,但遗憾的是不能在1.9.2
Apparently this used to work on ruby 1.8.7 but unfortunately not on 1.9.2
class String
def xor(key)
text = dup
text.length.times {|n| text[n] ^= key[n.modulo key.size] }
text
end
end
def encode(_original, _pass = 'testvendor')
_original.xor(_pass)
end
puts encode('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
#output=>
8
EE
DEBDREBDEVSR
TTTT
TNZV0D
SE E CRVSETENR D
TT
EKS0DSO VD
EVVTE S
RSREXE+E T
RR
T _TOEDE RO E
TTD
K
它返回
NoMethodError: undefined method `^' for "V":String
这是如何得到这个工作你知道吗?
Any idea on how to get this working?
非常感谢
推荐答案
在1.8时,的方法返回一个Fixnum对象这是指定索引处的字节。在1.9,的返回一个字符串。看起来你正在使用String作为字节的缓冲区,所以你应该在数组,而不是字符串工作:
In 1.8, the String#[]
method returned a Fixnum which was the byte at the specified index. In 1.9, String#[]
returns a String because strings are made of characters and the character-to-byte mapping depends on the encoding. Looks like you're using a String as a byte buffer so you should be working in Array instead of String:
class Array
def xor(key)
a = dup
a.length.times { |n| a[n] ^= key[n % key.size] }
a
end
end
然后使用它:
mangled_array = string.codepoints.to_a.xor(key.codepoints.to_a)
那么,如果你真的想要一个字符串(其中将包含一堆不可打印控制字符和零字节和这样的事情),那么:
Then if you really want a String (which will contain a bunch of unprintable control characters and zero bytes and such things), then:
mangled_string = mangled_array.inject('') { |s,c| s << c }
然后解压:
mangled_string.
codepoints.
to_a.
xor(key.codepoints.to_a).
inject('') { |s,c| s << c }
所有这一切都应该通过保持UTF-8所有的方式,这就是你想要的。
All of this should maintain UTF-8 all the way through and that's what you want.
您也许可以修补你的 XOR
成可枚举,如果需要跳过 to_a
业务。你很可能也适应这种打补丁的字符串为好。
You could probably patch your xor
into Enumerable and skip the to_a
business if desired. You could probably also adapt this to patch for String as well.
您不应该使用字节的缓冲区字符串中了,你最好使用Fixnum对象的数组关闭与明确的编码处理。
You shouldn't be using String for byte buffers anymore, you're better off using arrays of Fixnum for that with explicit encoding handling.
这篇关于简单的XOR红宝石1.9.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!