代码如下:
class RubyRc4
def initialize(str)
@q1, @q2 = 0, 0
@key = []
str.each_byte {|elem| @key << elem} while @key.size < 256
@key.slice!(256..@key.size-1) if @key.size >= 256
@s = (0..255).to_a
j = 0
0.upto(255) do |i|
j = (j + @s[i] + @key[i] )%256
@s[i], @s[j] = @s[j], @s[i]
end
end
def encrypt!(text)
process text
end
def encrypt(text)
process text.dup
end
private
def process(text)
0.upto(text.length-1) do |i|
text.setbyte(i, text.getbyte(i) ^ round)
end
text
end
def round
@q1 = (@q1 + 1)%256
@q2 = (@q2 + @s[@q1])%256
@s[@q1], @s[@q2] = @s[@q2], @s[@q1]
@s[(@s[@q1]+@s[@q2])%256]
end
end
str = '3f873a36c658'
key = '134df334ijnfd'
encryptor = RubyRc4.new(key)
decryptor = RubyRc4.new(key)
a = encryptor.encrypt(str)
b = decryptor.encrypt(a)
puts "a = #{a}"
puts "b = #{b}"
运行该文件后,加密后的密文 (a) 出现了乱码,但是解密后却能得到明文。
➜ code ruby rc4.rb
a = �;
)?�}��
b = 3f873a36c658
根据不同的明文与 key,会出现不同的乱码,尤其是某些时候,会出现"a="也变成乱码,比如:
➜ code ruby rc4.rb
f���5�64�
b = 3f873a36c658
也试过 base64 解码什么的,没用。本人小白一个,求大家帮忙看看吧。。。