Ruby 基于基本旋转的加密/解密问题

Ruby 基于基本旋转的加密/解密问题,ruby,encryption,rotation,irb,Ruby,Encryption,Rotation,Irb,基本上,我正在关注Jumpstart实验室的挑战加密程序,并遇到了一些问题 这是我的密码 class Encryptor def cipher(rotation) characters = (' '..'z').to_a rotated_characters = characters.rotate(rotation) Hash[characters.zip(rotated_characters)] end def encrypt_letter(letter,

基本上,我正在关注Jumpstart实验室的挑战加密程序,并遇到了一些问题

这是我的密码

class Encryptor
  def cipher(rotation)
    characters = (' '..'z').to_a
    rotated_characters = characters.rotate(rotation)
    Hash[characters.zip(rotated_characters)]
  end

  def encrypt_letter(letter, rotation)
    cipher_for_rotation = cipher(rotation)
    cipher_for_rotation[letter]
  end

  def encrypt(string, rotation)
    letters = string.split("")

    results = letters.collect do |letter|
        encrypt_letter = encrypt_letter(letter, rotation)
    end

    results.join
  end

  def decrypt_letter(letter, rotation)
    cipher_for_rotation = cipher(rotation)
    reversed_cipher = cipher_for_rotation.to_a.reverse.to_h
    reversed_cipher[letter]
  end

  def decrypt(string, rotation)
    letters = string.split("")

    results = letters.collect do |letter|
        decrypt_letter = decrypt_letter(letter, rotation)
    end

    results.join
  end
end
我的解密方法遇到了困难。以下是从irb粘贴的

2.3.0 :001 > load './encryptor.rb'
 => true
2.3.0 :002 > e = Encryptor.new
 => #<Encryptor:0x007fe93a0319b8>
2.3.0 :003 > encrypted = e.encrypt("Hello, World!", 10)
 => "Rovvy6*ay!vn+"
2.3.0 :004 > e.decrypt(encrypted, 10)
 => "\\y%%(@4k(+%x5"
2.3.0:001>加载'./encryptor.rb'
=>正确
2.3.0:002>e=Encryptor.new
=> #
2.3.0:003>加密=e.encrypt(“你好,世界!”,10)
=>“Rovvy6*ay!vn+”
2.3.0:004>e.解密(加密,10)
=>“\\y%%”(@4k(+%x5)

如您所见,当解密我的加密字符串时,它应该输出“Hello,World!”,我用它加密的内容,旋转10次。如果您不知道我在这里做错了什么,请提供任何帮助。

您只需查找散列的密钥即可

def decrypt_letter(letter, rotation)
  cipher_for_rotation = cipher(rotation)
  cipher_for_rotation.key(letter)
end
例如:

irb(main):003:0> e = Encryptor.new
=> #<Encryptor:0x007fbcea9b65c8>
irb(main):004:0> enc = e.encrypt "Hello, World!", 10
=> "Rovvy6*ay!vn+"
irb(main):005:0> e.decrypt enc, 10
=> "Hello, World!"
irb(main):003:0>e=Encryptor.new
=> #
irb(main):004:0>enc=e.encrypt“你好,世界!”,10
=>“Rovvy6*ay!vn+”
irb(主):005:0>e.decrypt enc,10
=>“你好,世界!”

my decrypt_letter函数肯定有问题。在irb中进行一些调试后,请检查以下内容:e.encrypt_letter('t',13)=>“&>e.decrypt_letter('&',13)=>“3”有比我的“.to_a.reverse.to_h”方法更好的方法吗?我承认我没有深入研究过你的代码,但你的解密和加密方法看起来不同这一事实对我来说是一个危险信号。(事实上,你甚至有两种方法都是可疑的。)从我对你的代码的理解来看,你正在实现一个凯撒密码,凯撒密码是完全对称的:加密和解密是完全相同的事情,只是使用不同的密钥。不应该有两种方法,当然也不应该有两种不同的加密和解密方法,因为两者都是完全对称的同样的。@JörgWMittag非常感谢您的回复,我在这里只是掌握了ruby的基本知识。我遵循以下教程:我想这会引导我实现您提到的方法,但首先显示了错误的方法?不确定。我肯定会听取您的建议并做更多的研究。基本上,
decrypt(10)
encrypt(-10)
相同,后者又与
encrypt(17)
(假设为27个字母)相同。更一般地说,
decrypt(N)=encrypt(-N)=encrypt(alphabet.size-N)
。这可能正是我想要的,谢谢你的输入。是的,这很好用。非常感谢