Advertisement
Guest User

Untitled

a guest
Nov 21st, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.31 KB | None | 0 0
  1. class PlayfairCipher
  2.   AZ = ('A'..'Z').to_a - ['J']
  3.   def initialize keyword
  4.     @square = keyword.upcase.gsub(/[^A-Z]/, '').gsub('J', 'I').split('').uniq
  5.     AZ.each{|x| @square.push x unless @square.include? x}
  6.     @square = 0.step(20, 5).collect{|x| @square.slice x,5}
  7.     @h = AZ.collect{|x| AZ.collect{|y| "'#{x+y}' => '#{convert x, y}'"}}.flatten.join ', '
  8.     @h = eval "{#{@h}}"
  9.     @rh = @h.invert
  10.   end
  11.  
  12.   attr_reader :square
  13.  
  14.   def convert a, b
  15.     ax, ay, bx, by, i = nil
  16.     @square.each.with_index do |line, j|
  17.       (ax, ay = i, j) if i = line.index(a)
  18.       (bx, by = i, j) if i = line.index(b)
  19.     end
  20.     case
  21.       when ay == by
  22.         @square[ay][(ax + 1) % 5] + @square[by][(bx + 1) % 5]
  23.       when ax == bx
  24.         @square[(ay + 1) % 5][ax] + @square[(by + 1) % 5][bx]
  25.       else
  26.         @square[ay][bx] + @square[by][ax]
  27.     end
  28.   end
  29.  
  30.   def insert_xz s
  31.     return [s, nil] if s.length < 2
  32.     xz = @flag ? 'Z' : 'X'
  33.     s[0] == s[1] ? (@flag = !@flag; [s[0, 1] + xz, s[1..-1]]) : (@flag = false; [s[0, 2], s[2..-1]])
  34.   end
  35.  
  36.   def encrypt str
  37.     s = str.upcase.gsub(/[^A-Z]/, '').gsub('J', 'I')
  38.     str = ''
  39.     (pair, s = insert_xz(s); str << pair) while s
  40.     str += 'X' unless (str.length % 2).zero?
  41.     str.gsub(/(..)/){$1+' '}.split.collect{|s| @h[s]}.join
  42.   end
  43. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement