Advertisement
Guest User

Untitled

a guest
May 26th, 2015
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. Plugboard = Hash[*('A'..'Z').to_a.sample(20)]
  2. Plugboard.merge!(Plugboard.invert)
  3. Plugboard.default_proc = proc { |_hash, key| key }
  4.  
  5. def build_a_rotor
  6. Hash[('A'..'Z').zip(('A'..'Z').to_a.shuffle)]
  7. end
  8.  
  9. ROTOR_1, ROTOR_2, ROTOR_3 = build_a_rotor, build_a_rotor, build_a_rotor
  10.  
  11. Reflector = Hash[*('A'..'Z').to_a.shuffle]
  12. Reflector.merge!(Reflector.invert)
  13.  
  14. def input(string)
  15. rotor_1, rotor_2, rotor_3 = ROTOR_1.dup, ROTOR_2.dup, ROTOR_3.dup
  16.  
  17. string.chars.each_with_index.map do |char, index|
  18. rotor_1 = rotate_rotor rotor_1
  19. rotor_2 = rotate_rotor rotor_2 if index % 25 == 0
  20. rotor_3 = rotate_rotor rotor_3 if index % 25 * 25 == 0
  21.  
  22. char = Plugboard[char]
  23.  
  24. char = rotor_1[char]
  25. char = rotor_2[char]
  26. char = rotor_3[char]
  27.  
  28. char = Reflector[char]
  29.  
  30. char = rotor_3.invert[char]
  31. char = rotor_2.invert[char]
  32. char = rotor_1.invert[char]
  33.  
  34. Plugboard[char]
  35. end.join
  36. end
  37.  
  38. def rotate_rotor(rotor)
  39. Hash[rotor.map { |k, v| [k == 'Z' ? 'A' : k.next, v] }]
  40. end
  41.  
  42. plain_text = 'IHAVETAKENMOREOUTOFALCOHOLTHANALCOHOLHASTAKENOUTOFME'
  43. puts "Encrypted '#{plain_text}' to '#{encrypted = input(plain_text)}'"
  44. puts "Decrypted '#{encrypted}' to '#{decrypted = input(encrypted)}'"
  45. puts 'Success!' if plain_text == decrypted
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement