Class: IOP::CipherEncryptor
- Inherits:
-
Object
- Object
- IOP::CipherEncryptor
- Defined in:
- lib/iop/openssl.rb
Overview
Filter class to perform encryption with a symmetric key algorithm (ciphering) of the data passed through.
The class is an adapter for OpenSSL::Cipher & compatible classes.
### Use case: generate 1024 bytes of random data encrypt is with default cipher algorithm and generated key & initial vector.
require 'iop/openssl'
require 'iop/securerandom'
( IOP::SecureRandomGenerator.new(1024) | (c = IOP::CipherEncryptor.new) ).process!
puts c.key
Instance Attribute Summary collapse
-
#iv ⇒ Object
readonly
Returns initial vector (IV) for encryption session.
-
#key ⇒ Object
readonly
Returns encryption key.
Attributes included from Sink
Attributes included from Feed
Instance Method Summary collapse
-
#initialize(cipher = DEFAULT_OPENSSL_CIPHER, key: nil, iv: nil) ⇒ CipherEncryptor
constructor
Creates class instance.
- #process(data = nil) ⇒ Object
Methods included from Sink
Methods included from Feed
Constructor Details
#initialize(cipher = DEFAULT_OPENSSL_CIPHER, key: nil, iv: nil) ⇒ CipherEncryptor
Creates class instance.
cipher can be either a String or OpenSSL::Cipher instance. If it is a string, a corresponding OpenSSL::Cipher instance will be created.
If key is nil, a new key will be generated in secure manner which can be accessed later with #key method.
If iv is nil, a new initial vector will be generated in secure manner which can be accessed later with #iv method. If iv is nil the generated initial vector will be injected into the downstream data preceding the encrypted data itself.
Note that key and initial vector are both cipher-dependent. Refer to OpenSSL::Cipher documentation for more information.
54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/iop/openssl.rb', line 54 def initialize(cipher = DEFAULT_OPENSSL_CIPHER, key: nil, iv: nil) @cipher = cipher.is_a?(String) ? OpenSSL::Cipher.new(cipher) : cipher @cipher.encrypt @key = key.nil? ? @cipher.random_key : @cipher.key = key @iv = if iv.nil? @embed_iv = true @cipher.random_iv else @cipher.iv = iv end end |
Instance Attribute Details
#iv ⇒ Object (readonly)
Returns initial vector (IV) for encryption session.
32 33 34 |
# File 'lib/iop/openssl.rb', line 32 def iv @iv end |
#key ⇒ Object (readonly)
Returns encryption key.
35 36 37 |
# File 'lib/iop/openssl.rb', line 35 def key @key end |
Instance Method Details
#process(data = nil) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/iop/openssl.rb', line 66 def process(data = nil) unless @continue @continue = true super(iv) if @embed_iv @buffer = IOP.allocate_string(data.size) end if data.nil? super(@cipher.final) super else super(@cipher.update(data, @buffer)) unless data.size.zero? end end |