Class: CoderDecorator::Coders::Cipher
- Defined in:
- lib/coder_decorator/coders/cipher.rb
Overview
Encrypt the data into this format:
"#{encrypted_data}--#{initial_vector}"
Constant Summary
Constants inherited from Coder
CoderDecorator::Coders::Coder::DELEGATE
Instance Method Summary collapse
- #decode(str) ⇒ Object
- #encode(obj) ⇒ Object
-
#initialize(coder = nil, secret:, old_secret: nil, cipher: 'AES-256-CBC') ⇒ Cipher
constructor
A new instance of Cipher.
Methods inherited from Coder
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 19 |
# 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) @base64 = Coders::Base64.new end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class CoderDecorator::Coders::Coder
Instance Method Details
#decode(str) ⇒ Object
30 31 32 33 34 35 36 37 38 39 |
# File 'lib/coder_decorator/coders/cipher.rb', line 30 def decode(str) [@secret, @old_secret].each do |secret| begin return decrypt(secret, str) rescue ::OpenSSL::Cipher::CipherError, ::TypeError next end end raise InvalidEncoding end |
#encode(obj) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/coder_decorator/coders/cipher.rb', line 21 def encode(obj) @cipher.encrypt @cipher.key = @secret iv = @cipher.random_iv encrypted_data = @cipher.update(coder.encode(obj)) << @cipher.final blob = "#{@base64.encode(encrypted_data)}--#{@base64.encode(iv)}" @base64.encode(blob) end |