class IOP::CipherEncryptor

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

@since 0.1

Attributes

iv[R]

Returns initial vector (IV) for encryption session.

key[R]

Returns encryption key.

Public Class Methods

new(cipher = DEFAULT_OPENSSL_CIPHER, key: nil, iv: nil) click to toggle source

Creates class instance.

@param cipher [String, OpenSSL::Cipher] cipher used for encryption

@param key [String] string representing an encryption key or nil

@param iv [String] string representing an initial vector or nil

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.

# 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

Public Instance Methods

process(data = nil) click to toggle source
Calls superclass method IOP::Sink#process
# 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