Class: Encrypted::Ciph

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

Constant Summary collapse

MODE_KEYS =
[128,192,256]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mode) ⇒ Ciph

Returns a new instance of Ciph.



9
10
11
# File 'lib/encrypted.rb', line 9

def initialize(mode)
  decode_mode mode
end

Instance Attribute Details

#ivObject

Returns the value of attribute iv.



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

def iv
  @iv
end

#keyObject

Returns the value of attribute key.



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

def key
  @key
end

Class Method Details

.modesObject



41
42
43
44
45
46
47
48
# File 'lib/encrypted.rb', line 41

def self.modes
  modes_array = []
  MODE_KEYS.each do |k|
    a_mode = "'"+k.to_s
    MODE_KEYS.each {|kk| modes_array << a_mode + '-'+ kk.to_s + "'"}
  end
  modes_array.join(', ')
end

Instance Method Details

#decode_mode(mode) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/encrypted.rb', line 29

def decode_mode(mode)
  mode_array = mode.split('-')
  key_length = mode_array[0].to_i if mode_array[0]
  iv_length = mode_array[1].to_i if mode_array[1]
  if (MODE_KEYS.include? key_length) && (MODE_KEYS.include? iv_length)
    @key_length = key_length
    @iv_length = iv_length
  else
    raise "Mode '#{mode}' is invalid. Please provide one of these #{self.class.modes}"
  end
end

#decrypt(encrypted_text) ⇒ Object



65
66
67
68
69
70
# File 'lib/encrypted.rb', line 65

def decrypt(encrypted_text)
  raise "Cannot decrypt without key and/or iv" unless @key && @iv
  cipher = Encrypted::Rijndael.new(@key)
  cbc = Encrypted::CBC.new(cipher)
  cbc.decrypt(@iv, encrypted_text)
end

#encrypt(plain_text) ⇒ Object



58
59
60
61
62
63
# File 'lib/encrypted.rb', line 58

def encrypt(plain_text)
  raise "Cannot encrypt without key and/or iv" unless @key && @iv
  cipher = Encrypted::Rijndael.new(@key)
  cbc = Encrypted::CBC.new(cipher)
  cbc.encrypt(@iv, plain_text)
end

#generate_ivObject



50
51
52
# File 'lib/encrypted.rb', line 50

def generate_iv
  @iv = SecureRandom.random_bytes(@iv_length/8)
end

#generate_keyObject



54
55
56
# File 'lib/encrypted.rb', line 54

def generate_key
  @key = SecureRandom.random_bytes(@key_length/8)
end