Class: ActiveCrypto::Encryptor

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(field, options = {}) ⇒ Encryptor

Returns a new instance of Encryptor.



9
10
11
12
13
14
15
# File 'lib/active_crypto/encryptor.rb', line 9

def initialize(field, options = {})

  @field = field
  @options = {:cipher     => 'AES',
              :block_mode => 'CBC',
              :keylength  => 256}.merge(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/active_crypto/encryptor.rb', line 7

def options
  @options
end

Instance Method Details

#after_save(model) ⇒ Object Also known as: after_find



24
25
26
27
28
29
# File 'lib/active_crypto/encryptor.rb', line 24

def after_save(model)
  unless model[@field].blank?
    key = model.class.encryption_key
    model[@field] = decrypt(model[@field], key, @options)
  end
end

#algorithm(opts) ⇒ Object



51
52
53
# File 'lib/active_crypto/encryptor.rb', line 51

def algorithm(opts)
  "#{opts[:cipher]}-#{opts[:keylength]}-#{opts[:block_mode]}"
end

#before_save(model) ⇒ Object



17
18
19
20
21
22
# File 'lib/active_crypto/encryptor.rb', line 17

def before_save(model)
  unless model[@field].blank?
    key = model.class.encryption_key
    model[@field] = encrypt(model[@field], key, @options)
  end
end

#decrypt(text, key, opt) ⇒ Object



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

def decrypt(text, key, opt)
  decipher = OpenSSL::Cipher.new(algorithm(opt))
  decipher.decrypt
  decoded_text = Base64.decode64(text)
  decipher.key = key
  decipher.iv  = decoded_text.slice!(0..15)
  decrypted = decipher.update(decoded_text)
  decrypted << decipher.final
end

#encrypt(text, key, opt) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/active_crypto/encryptor.rb', line 31

def encrypt(text, key, opt)
  cipher = OpenSSL::Cipher.new(algorithm(opt))
  cipher.encrypt
  cipher.key = key
  iv = cipher.random_iv
  encrypted = cipher.update(text) + cipher.final
  encrypted.insert(0, iv)
  Base64.encode64(encrypted)
end