【问题标题】:Ruby error: in `block in process': undefined method `^' for "4":String (NoMethodError)Ruby 错误:在“进程中的块”中:“4”的未定义方法“^”:字符串(NoMethodError)
【发布时间】:2014-10-07 19:39:09
【问题描述】:

尝试运行 rc4 算法但无法识别 XOR 方法?还是发生了其他事情?当它到达 def process(text) 时出现错误。

错误:

rc4.rb:26:in block in process': undefined method^' for "4":String (NoMethodError) 来自 rc4.rb:26:in upto' from rc4.rb:26:inprocess' 来自 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

【问题讨论】:

  • 你有什么问题?
  • 为什么会出现这个错误/为什么它不能运行?
  • 我之前在 RC4 上工作过,你可以在这里看到代码:github.com/suryart/spree_ebsin/blob/master/lib/spree_ebsin/…
  • 0.upto(text.length-1) {|i| text[i] = text[i] ^ round} 将不起作用,因为您尝试使用字符串:text[i] 在表达式中:text[i] ^ round 它应该是 text[i].to_i ^ round 或其他东西。
  • 试过了,然后开始收到另一个错误,我在下面的 cmets 中发布了其他响应。

标签: ruby rc4-cipher


【解决方案1】:

text[i] 在这里是一个字符串。使用text[i].to_i

这应该可以工作

0.upto(text.length-1) {|i| text[i] = (text[i].ord ^ round).chr}

由于您正在进行加密,将“4”转换为 4 将是一个错误。我们对编码进行操作并将其转换回来。

【讨论】:

  • rc4.rb:27:in []=': no implicit conversion of Fixnum into String (TypeError) from rc4.rb:27:in block in process' 来自 rc4.rb:27:in upto' from rc4.rb:27:in process' 来自 rc4.rb:21:in encrypt' from rc4.rb:49:in
    '
  • github.com/maxprokopiev/ruby-rc4 拿到这个,所以我认为它应该可以工作
  • 好的,这个版本运行了,现在如何让密文显示为普通数字?这就是我得到的:明文是:123 11 81 99 232 5 密文是:ƻ?~??K??????6?解密文本为:123 11 81 99 232 5
  • 你输入了什么?
  • 输入键。 1234 5678 输入明文。 9876 5432 明文为:9876 5432 密文为:??T:?A?@s 解密后的文本为:9876 5432
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多