Advertisement
t_a_w

Monkey encrypt 2

Nov 1st, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.27 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 == 0
  29.       return nil
  30.     elsif possibles.size == 1
  31.       pt[i] = possibles[0].chr
  32.     else
  33.       pt[i] = "(" + possibles.map(&:chr).join("|") + ")"
  34.     end
  35.     key += 1
  36.   end
  37.  
  38.   pt.join
  39.  end
  40.  
  41. ciphertext = %W[102 141 142 161 148 131 158 157 120 131 126 153 130 143 154 135 118 137 148 111 116 145 134 133 118 103 136 107 138 127 102 131 194 99 114 200 202 127 120 105 126 202 108 194 198 214 222 204 116 224 194 198 202 230 166 222 216 234 232 210 222 220 210 230 194 230 198 210 210 230 234 218 222 204 194 216 216 224 216 194 210 220 232 202 240 232 198 208 194 228 230].map(&:to_i).map(&:chr).join
  42.  
  43. (0..(ciphertext.size / 2)).each do |key|
  44.   replaintext = decrypt(ciphertext, key)
  45.   p key
  46.   p replaintext
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement