Class: Cifrado::CryptoEngineAES

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

Overview

Shamelessly stolen from Gibberish, from Mark Percival so I don’t have to depend on yet another gem.

See: github.com/mdp/gibberish

Added a few small modifications:

  • Use Base64 urlsafe_encode/decode

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(password, size = 256) ⇒ CryptoEngineAES

Initialize with the password

Parameters:

  • password (String)
  • size (Integer) (defaults to: 256)


175
176
177
178
179
# File 'lib/cifrado/crypto_services.rb', line 175

def initialize(password, size=256)
  @password = password
  @size = size
  @cipher = OpenSSL::Cipher::Cipher.new("aes-#{size}-cbc")
end

Instance Attribute Details

#cipherObject (readonly)

Returns the value of attribute cipher.



169
170
171
# File 'lib/cifrado/crypto_services.rb', line 169

def cipher
  @cipher
end

#passwordObject (readonly)

Returns the value of attribute password.



169
170
171
# File 'lib/cifrado/crypto_services.rb', line 169

def password
  @password
end

#sizeObject (readonly)

Returns the value of attribute size.



169
170
171
# File 'lib/cifrado/crypto_services.rb', line 169

def size
  @size
end

Instance Method Details

#decrypt(data, opts = {}) ⇒ Object Also known as: dec, d



191
192
193
194
195
196
197
# File 'lib/cifrado/crypto_services.rb', line 191

def decrypt(data, opts={})
  data = Base64.urlsafe_decode64(data) unless opts[:binary]
  salt = data[8..15]
  data = data[16..-1]
  setup_cipher(:decrypt, salt)
  cipher.update(data) + cipher.final
end

#encrypt(data, opts = {}) ⇒ Object Also known as: enc, e



181
182
183
184
185
186
187
# File 'lib/cifrado/crypto_services.rb', line 181

def encrypt(data, opts={})
  salt = generate_salt(opts[:salt])
  setup_cipher(:encrypt, salt)
  e = cipher.update(data) + cipher.final
  e = "Salted__#{salt}#{e}" #OpenSSL compatible
  opts[:binary] ? e : Base64.urlsafe_encode64(e)
end