Class: Pontifex::Cipher

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

Instance Method Summary collapse

Constructor Details

#initialize(str, deck_key = nil) ⇒ Cipher

Returns a new instance of Cipher.



5
6
7
8
# File 'lib/pontifex/cipher.rb', line 5

def initialize(str, deck_key=nil)
  @raw = str
  @keystream = deck_key.nil? ? KeyStream.new : KeyStream.new(deck_key)
end

Instance Method Details

#decryptedObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pontifex/cipher.rb', line 28

def decrypted
  @keystream.sequence!
  processed = @raw.upcase.gsub(/[^A-Z]/, "")

  results = ""
  processed.each_char do |c|
    k = @keystream.letter
    if (c.ord - 64) <= (k.ord - 64)
      value = (c.ord - 64 + 26) - (k.ord - 64)
    else
      value = (c.ord - 64) - (k.ord - 64)
    end
    results << (value + 64).chr
    @keystream.sequence!
  end

  output_str = ""
  results.scan(/.{5}/).each_slice(5) { |s| output_str << s.join(" ") + "\n" }
  output_str.chomp
end

#encryptedObject



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

def encrypted
  @keystream.sequence!
  processed = @raw.upcase.gsub(/[^A-Z]/, "")
  processed << "X" * (5 - (processed.length % 5)) unless (processed.length % 5) == 0

  results = ""
  processed.each_char do |c|
    k = @keystream.letter
    value = (c.ord - 64) + (k.ord - 64)
    results << ((value > 26 ? value - 26 : value) + 64).chr
    @keystream.sequence!
  end

  output_str = ""
  results.scan(/.{5}/).each_slice(5) { |s| output_str << s.join(" ") + "\n" }
  output_str.chomp
end