Class: ChaoCipher::Cipher

Inherits:
Object
  • Object
show all
Defined in:
lib/chaocipher/cipher.rb

Instance Method Summary collapse

Constructor Details

#initialize(ciphertext_alphabet, plaintext_alphabet) ⇒ Cipher

Returns a new instance of Cipher.



3
4
5
6
7
8
# File 'lib/chaocipher/cipher.rb', line 3

def initialize(ciphertext_alphabet, plaintext_alphabet)
  @original_ciphertext_alphabet = ciphertext_alphabet
  @original_plaintext_alphabet = plaintext_alphabet
  @ciphertext_alphabet = Alphabet.new(ciphertext_alphabet.upcase.chars.to_a, :ciphertext)
  @plaintext_alphabet = Alphabet.new(plaintext_alphabet.upcase.chars.to_a, :plaintext)
end

Instance Method Details

#cipher(mode, text) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/chaocipher/cipher.rb', line 23

def cipher(mode, text)
  reinitialize!
  
  converted_text = ""
  
  text.chars.each do |character|
    if mode == :encrypt
      @last_converted_letter = ciphertext_letter_for(character)
      @ciphertext_alphabet.permute!(@last_converted_letter)
      @plaintext_alphabet.permute!(character)
    else
      @last_converted_letter = plaintext_letter_for(character)
      @ciphertext_alphabet.permute!(character)
      @plaintext_alphabet.permute!(@last_converted_letter)
    end
    
    converted_text << @last_converted_letter
  end
  
  converted_text
end

#ciphertext_letter_for(plaintext_letter) ⇒ Object



19
20
21
# File 'lib/chaocipher/cipher.rb', line 19

def ciphertext_letter_for(plaintext_letter)
  @ciphertext_alphabet.characters[@plaintext_alphabet.characters.index(plaintext_letter)]
end

#decrypt(ciphertext) ⇒ Object



49
50
51
# File 'lib/chaocipher/cipher.rb', line 49

def decrypt(ciphertext)
  cipher(:decrypt, ciphertext)
end

#encrypt(plaintext) ⇒ Object



45
46
47
# File 'lib/chaocipher/cipher.rb', line 45

def encrypt(plaintext)
  cipher(:encrypt, plaintext)
end

#plaintext_letter_for(ciphertext_letter) ⇒ Object



15
16
17
# File 'lib/chaocipher/cipher.rb', line 15

def plaintext_letter_for(ciphertext_letter)
  @plaintext_alphabet.characters[@ciphertext_alphabet.characters.index(ciphertext_letter)]
end

#reinitialize!Object



10
11
12
13
# File 'lib/chaocipher/cipher.rb', line 10

def reinitialize!
  @ciphertext_alphabet = Alphabet.new(@original_ciphertext_alphabet.upcase.chars.to_a, :ciphertext)
  @plaintext_alphabet = Alphabet.new(@original_plaintext_alphabet.upcase.chars.to_a, :plaintext)
end