Class: VigenereCipher

Inherits:
Object
  • Object
show all
Includes:
Math
Defined in:
lib/vigenere_cipher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(word = nil) ⇒ VigenereCipher

Returns a new instance of VigenereCipher.



6
7
8
9
# File 'lib/vigenere_cipher.rb', line 6

def initialize(word = nil)
  word ||= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  @table_recta = word
end

Instance Attribute Details

#table_rectaObject

Returns the value of attribute table_recta.



4
5
6
# File 'lib/vigenere_cipher.rb', line 4

def table_recta
  @table_recta
end

Instance Method Details

#decode(cipher_text, key) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/vigenere_cipher.rb', line 27

def decode(cipher_text, key)
  
  return nil if key_validate(key) == false
  
  key_index = 0;
  cipher_text.each_char.inject("") do |s, c|
    index = get_plain_char_index_in_table_recta(c, key, key_index)
    if index.nil?
      return nil
    else
      key_index = next_key_index(key, key_index)
      s += @table_recta[index]
    end
  end
end

#encode(plain_text, key) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/vigenere_cipher.rb', line 11

def encode(plain_text, key)
  
  return nil if key_validate(key) == false
  
  key_index = 0;
  plain_text.each_char.inject("") do |s, c|
    index = get_cipher_char_index_in_table_recta(c, key, key_index)
    if index.nil?
      return nil
    else
      key_index = next_key_index(key, key_index)
      s += @table_recta[index]
    end
  end
end