Class: CoderDecorator::Coders::Cipher
- Defined in:
- lib/coder_decorator/coders/cipher.rb
Overview
Encrypt the data into this format:
"#{encrypted_data}--#{initial_vector}"
Instance Attribute Summary
Attributes inherited from Coder
Instance Method Summary collapse
- #decode(data) ⇒ Object
- #encode(obj) ⇒ Object
-
#initialize(coder = nil, secret:, old_secret: nil, cipher: 'AES-256-CBC') ⇒ Cipher
constructor
A new instance of Cipher.
Constructor Details
#initialize(coder = nil, secret:, old_secret: nil, cipher: 'AES-256-CBC') ⇒ Cipher
Returns a new instance of Cipher.
13 14 15 16 17 18 |
# File 'lib/coder_decorator/coders/cipher.rb', line 13 def initialize(coder = nil, secret:, old_secret: nil, cipher: 'AES-256-CBC') super(coder) @secret = secret @old_secret = old_secret @cipher = OpenSSL::Cipher.new(cipher) end |
Instance Method Details
#decode(data) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/coder_decorator/coders/cipher.rb', line 28 def decode(data) secrets = [@old_secret, @secret] until secrets.empty? secret = secrets.pop begin encrypted_data, iv = data.split('--').map! { |v| v.unpack('m0').first } @cipher.decrypt @cipher.key = secret @cipher.iv = iv return coder.decode(@cipher.update(encrypted_data) << @cipher.final) rescue StandardError secrets.empty? ? raise : next end end end |
#encode(obj) ⇒ Object
20 21 22 23 24 25 26 |
# File 'lib/coder_decorator/coders/cipher.rb', line 20 def encode(obj) @cipher.encrypt @cipher.key = @secret iv = @cipher.random_iv encrypted_data = @cipher.update(coder.encode(obj)) << @cipher.final "#{[encrypted_data].pack('m0')}--#{[iv].pack('m0')}" end |