Class: Eaesy::Cipher

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

Instance Method Summary collapse

Constructor Details

#initialize(key_plain) ⇒ Cipher

Returns a new instance of Cipher.



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

def initialize(key_plain)
  @cipherAlg = "aes-256-cbc"
  @key = sha256(key_plain)
end

Instance Method Details

#decrypt(encrypted_secret, iv) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/eaesy.rb', line 37

def decrypt(encrypted_secret, iv)
  # now we create a cipher for decrypting
  cipher = OpenSSL::Cipher.new(@cipherAlg)
  cipher.decrypt
  cipher.key = @key
  cipher.iv = iv.unpack('m')[0]

  # and decrypt it
  decrypted = cipher.update(encrypted_secret.unpack('m')[0])
  decrypted << cipher.final

  decrypted
end

#encrypt(secret, iv = nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/eaesy.rb', line 14

def encrypt(secret, iv = nil)
  cipher = OpenSSL::Cipher.new(@cipherAlg)
  cipher.encrypt

  # you will need to store this and key for later, in order to decrypt your data
  iv = iv.unpack('m')[0] if iv
  iv = cipher.random_iv unless iv

  # load them into the cipher
  cipher.key = @key
  cipher.iv = iv

  secret = ' ' if (secret || '').length == 0
  # encrypt the message
  encrypted = cipher.update(secret)
  encrypted << cipher.final

  {
    encrypted_secret: [encrypted].pack('m'),
    iv: [iv].pack('m')
  }
end