尝试运行 rc4 算法但无法识别 XOR 方法?还是发生了其他事情?当它到达 def process(text) 时出现错误。
错误:
rc4.rb:26:in block in process': undefined method
^' for "4":String (NoMethodError) from rc4.rb:26:in upto'
from rc4.rb:26:in
process' from rc4.rb:21:in encrypt'
from rc4.rb:48:in
'
代码:
class Rc4
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) {|i| text[i] = text[i] ^ round}
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
puts "Enter key."
keyInput = gets.chomp
keyInput = keyInput.to_s
encryptInstance = Rc4.new(keyInput)
decryptInstance = Rc4.new(keyInput)
puts "Enter plaintext."
plainInput = gets.chomp
plainInput = plainInput.to_s
cipherText = encryptInstance.encrypt(plainInput)
puts "Plaintext is: " + plainInput
puts "Ciphertext is: " + cipherText
decryptedText = decryptInstance.encrypt(cipherText)
puts "Decrypted text is: " + decryptedText