Module: SecureAttribute

Defined in:
lib/secure_attribute.rb,
lib/secure_attribute/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.1.2"

Class Method Summary collapse

Class Method Details

.decipher(data, key) ⇒ Object



14
15
16
17
# File 'lib/secure_attribute.rb', line 14

def self.decipher(data, key)
  algorithm, iv, data = SecureAttribute.unpack(data)
  SecureAttribute.decrypt(algorithm, data, key, iv)
end

.decrypt(algorithm, data, key, iv) ⇒ Object



26
27
28
29
30
31
# File 'lib/secure_attribute.rb', line 26

def self.decrypt(algorithm, data, key, iv)
  cipher = OpenSSL::Cipher.new(algorithm).decrypt
  cipher.key, cipher.iv = key, iv
  decrypted = cipher.update(data)
  decrypted << cipher.final
end

.encipher(algorithm, data, key) ⇒ Object



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

def self.encipher(algorithm, data, key)
  encrypted, iv = SecureAttribute.encrypt(algorithm, data, key)
  SecureAttribute.pack(algorithm, iv, encrypted)
end

.encrypt(algorithm, data, key) ⇒ Object



19
20
21
22
23
24
# File 'lib/secure_attribute.rb', line 19

def self.encrypt(algorithm, data, key)
  cipher = OpenSSL::Cipher.new(algorithm).encrypt
  cipher.key = key
  iv = cipher.random_iv
  [cipher.update(data) + cipher.final, iv]
end

.export_random_key_base64(algorithm) ⇒ Object



42
43
44
# File 'lib/secure_attribute.rb', line 42

def self.export_random_key_base64(algorithm)
  Base64.strict_encode64(OpenSSL::Cipher.new(algorithm).random_key)
end

.included(model) ⇒ Object



5
6
7
# File 'lib/secure_attribute.rb', line 5

def self.included(model)
  model.extend(ClassMethods)
end

.pack(algorithm, iv, encrypted) ⇒ Object



33
34
35
# File 'lib/secure_attribute.rb', line 33

def self.pack(algorithm, iv, encrypted)
  ["", algorithm, Base64.strict_encode64(iv), Base64.strict_encode64(encrypted)].join("$")
end

.unpack(string) ⇒ Object



37
38
39
40
# File 'lib/secure_attribute.rb', line 37

def self.unpack(string)
  _, algorithm, iv, data = string.split("$")
  [algorithm, Base64.decode64(iv), Base64.decode64(data)]
end