Advertisement
t_a_w

monkey encrypts

Nov 1st, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.89 KB | None | 0 0
  1. require "pp"
  2.  
  3. def encrypt(plaintext, key)
  4.   pt = plaintext
  5.   key += pt.length / 2
  6.   ct = Array.new(pt.size)
  7.  
  8.   (0..pt.size-1).each do |i|
  9.     ct[i] = pt[i].ord + ( pt[i].ord % key )
  10.     key += 1
  11.   end
  12.  
  13.   ct.map(&:chr).join
  14. end
  15.  
  16. def decrypt(ciphertext, key)
  17.   ct = ciphertext
  18.   key += ct.length / 2
  19.   pt = Array.new(ct.size)
  20.  
  21.   (0..pt.size-1).each do |i|
  22.     possibles = []
  23.     (0..127).each do |possible_pt|
  24.       if possible_pt + (possible_pt % key) == ct[i].ord
  25.         possibles << possible_pt
  26.       end
  27.     end
  28.     if possibles.size == 1
  29.       pt[i] = possibles[0].chr
  30.     else
  31.       pt[i] = "(" + possibles.map(&:chr).join("|") + ")"
  32.     end
  33.     key += 1
  34.   end
  35.  
  36.   pt.join
  37.  end
  38.  
  39. plaintext = "Hello, world!"
  40. key = rand(plaintext.size / 2)
  41. ciphertext = encrypt(plaintext, key)
  42. replaintext = decrypt(ciphertext, key)
  43.  
  44. p key
  45. p plaintext
  46. p ciphertext
  47. p replaintext
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement