Class: Megar::Crypto::Aes

Inherits:
Object
  • Object
show all
Defined in:
lib/megar/crypto/aes.rb

Overview

A convenience wrapper for AES CBC implementation provided by OpenSSL

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Aes

Returns a new instance of Aes.



7
8
9
10
# File 'lib/megar/crypto/aes.rb', line 7

def initialize(options={})
  self.key = options[:key]
  self.iv = options[:iv]
end

Instance Attribute Details

#ivObject

Returns the value of attribute iv.



5
6
7
# File 'lib/megar/crypto/aes.rb', line 5

def iv
  @iv
end

#keyObject

Returns the value of attribute key.



4
5
6
# File 'lib/megar/crypto/aes.rb', line 4

def key
  @key
end

Instance Method Details

#cipherObject



28
29
30
# File 'lib/megar/crypto/aes.rb', line 28

def cipher
  @cipher ||= OpenSSL::Cipher::Cipher.new(mode)
end

#decrypt(data) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/megar/crypto/aes.rb', line 46

def decrypt(data)
  a32_mode = data.is_a?(Array)
  d = a32_mode ? data.pack(packing) : data

  cipher.reset
  cipher.decrypt
  cipher.padding = 0
  cipher.iv = iv
  cipher.key = key
  result = cipher.update d

  a32_mode ? result.unpack(packing) : result
end

#encrypt(data) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/megar/crypto/aes.rb', line 32

def encrypt(data)
  a32_mode = data.is_a?(Array)
  d = a32_mode ? data.pack(packing) : data

  cipher.reset
  cipher.encrypt
  cipher.padding = 0
  cipher.iv = iv
  cipher.key = key
  result = cipher.update d

  a32_mode ? result.unpack(packing) : result
end

#modeObject



24
25
26
# File 'lib/megar/crypto/aes.rb', line 24

def mode
  'AES-128-CBC'
end

#packingObject



20
21
22
# File 'lib/megar/crypto/aes.rb', line 20

def packing
  'l>*'
end