class ActiveCrypto::Encryptor

Attributes

options[R]

Public Class Methods

new(field, options = {}) click to toggle source
# 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

Public Instance Methods

after_find(model)
Alias for: after_save
after_save(model) click to toggle source
# 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
Also aliased as: after_find
algorithm(opts) click to toggle source
# File lib/active_crypto/encryptor.rb, line 51
def algorithm(opts)
  "#{opts[:cipher]}-#{opts[:keylength]}-#{opts[:block_mode]}"
end
before_save(model) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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