Class: EnigmaEngine::Engine
Direct Known Subclasses
Crack
Instance Attribute Summary collapse
Instance Method Summary
collapse
#blue, #colorize, #date_valid?, #fields_empty?, #files_valid?, #green, #key_valid?, #red, #today, #yellow
#create_write_file, #open_file, #show_msg, #text_to_array
Methods included from Offsets
#a_offset, #b_offset, #c_offset, #d_offset, #get_date
Methods included from Rotors
#a_rotation, #b_rotation, #c_rotation, #d_rotation, #key, #put_key
Instance Attribute Details
#date ⇒ Object
Returns the value of attribute date.
14
15
16
|
# File 'lib/enigma_engine/engine.rb', line 14
def date
@date
end
|
#key=(value) ⇒ Object
13
14
15
|
# File 'lib/enigma_engine/engine.rb', line 13
def key=(value)
@key = value
end
|
Instance Method Details
#characters ⇒ Object
23
24
25
|
# File 'lib/enigma_engine/engine.rb', line 23
def characters
('a'..'z').to_a + ('0'..'9').to_a + [32.chr, 46.chr, 44.chr]
end
|
#decrypt(file, new_file, key, date) ⇒ Object
69
70
71
72
73
74
75
76
77
78
79
80
81
|
# File 'lib/enigma_engine/engine.rb', line 69
def decrypt(file, new_file, key, date)
@key = key
@date = date
message = text_to_array(open_file(file))
decrypted_chars = []
message.each do |row|
row.each_with_index do |item, index|
reversed = handle_rotation(index, item, method(:decrypt_char))
decrypted_chars.push(reversed)
end
end
create_write_file(decrypted_chars.join(''), new_file, key, date)
end
|
#decrypt_char(char, pos) ⇒ Object
34
35
36
37
38
39
40
|
# File 'lib/enigma_engine/engine.rb', line 34
def decrypt_char(char, pos)
char.downcase!
pos *= -1
char_map_hash = Hash[characters.zip(characters.rotate(pos))]
res = char.chars.map { |c| char_map_hash.fetch(c) }
res.join('')
end
|
#encrypt(file, new_file) ⇒ Object
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# File 'lib/enigma_engine/engine.rb', line 55
def encrypt(file, new_file)
@key = rand_key
@date = today
message = text_to_array(open_file(file))
encrypted_chars = []
message.each do |row|
row.each_with_index do |item, index|
rotated = handle_rotation(index, item, method(:encrypt_char))
encrypted_chars.push(rotated)
end
end
create_write_file(encrypted_chars.join(''), new_file, @key, date, true)
end
|
#encrypt_char(char, pos) ⇒ Object
27
28
29
30
31
32
|
# File 'lib/enigma_engine/engine.rb', line 27
def encrypt_char(char, pos)
char.downcase!
char_map_hash = Hash[characters.zip(characters.rotate(pos))]
res = char.chars.map { |c| char_map_hash.fetch(c) }
res.join('')
end
|
#handle_rotation(index, item, func) ⇒ Object
42
43
44
45
46
47
48
49
|
# File 'lib/enigma_engine/engine.rb', line 42
def handle_rotation(index, item, func)
case index
when 0 then func.call(item, a_rotation + a_offset)
when 1 then func.call(item, b_rotation + b_offset)
when 2 then func.call(item, c_rotation + c_offset)
when 3 then func.call(item, d_rotation + d_offset)
end
end
|
#rand_key ⇒ Object
51
52
53
|
# File 'lib/enigma_engine/engine.rb', line 51
def rand_key
rand(999_99).to_s.center(5, rand(9).to_s)
end
|