Class: Enygma::Encryptor

Inherits:
Object
  • Object
show all
Includes:
Confirmation
Defined in:
lib/enygma/encryptor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Confirmation

#show_confirmation_message

Constructor Details

#initialize(filename, cypher_filename = nil) ⇒ Encryptor

Returns a new instance of Encryptor.



13
14
15
16
17
18
19
20
# File 'lib/enygma/encryptor.rb', line 13

def initialize(filename, cypher_filename = nil)
  @filename = filename
  @cypher_filename = cypher_filename
  @encryption_key =  rand(10**5).to_s.rjust(5, '0')
  @encryption_date = Time.now.strftime("%d%m%y")
  @offset = Offset.get_offset(@encryption_date)
  @encrypted = ""
end

Instance Attribute Details

#cypher_filenameObject (readonly)

Returns the value of attribute cypher_filename.



10
11
12
# File 'lib/enygma/encryptor.rb', line 10

def cypher_filename
  @cypher_filename
end

#encryptedObject (readonly)

Returns the value of attribute encrypted.



10
11
12
# File 'lib/enygma/encryptor.rb', line 10

def encrypted
  @encrypted
end

#encryption_dateObject (readonly)

Returns the value of attribute encryption_date.



10
11
12
# File 'lib/enygma/encryptor.rb', line 10

def encryption_date
  @encryption_date
end

#encryption_keyObject (readonly)

Returns the value of attribute encryption_key.



10
11
12
# File 'lib/enygma/encryptor.rb', line 10

def encryption_key
  @encryption_key
end

#filenameObject (readonly)

Returns the value of attribute filename.



10
11
12
# File 'lib/enygma/encryptor.rb', line 10

def filename
  @filename
end

#offsetObject (readonly)

Returns the value of attribute offset.



10
11
12
# File 'lib/enygma/encryptor.rb', line 10

def offset
  @offset
end

Instance Method Details

#encryptObject



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

def encrypt
  begin
    plain_characters = Filer.read(@filename)
    plain_characters.each_slice(4) { |batch| encrypt_batch(batch) }
    @cypher_filename = Filer.write(
      @cypher_filename,
      @encrypted,
      @filename,
      "encrypted"
    )

    show_confirmation_message(
      @cypher_filename,
      @encryption_key,
      @encryption_date
    )
  rescue StandardError => e
    puts "Could not open the file you supplied."\
    "Make sure you are correctly typing the correct path. #{e.message}"
  end
end

#encrypt_batch(batch) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/enygma/encryptor.rb', line 44

def encrypt_batch(batch)
  key_characters = @encryption_key.split('')
  offset_characters = @offset.split('')
  batch.each_with_index do |_value, index|
    new_index = Rotator.rotate(
      key_characters[index],
      key_characters[index + 1],
      offset_characters[index],
      batch[index]
    ) { |x, y| x + y }

    @encrypted += Enygma::CHARACTER_MAP[new_index]
  end
end