Class: IOP::CipherDecryptor

Inherits:
Object
  • Object
show all
Includes:
Feed, Sink
Defined in:
lib/iop/openssl.rb

Overview

Filter class to perform decryption with a symmetric key algorithm (ciphering) of the data passed through.

The class is an adapter for OpenSSL::Cipher & compatible classes.

### Use case: decrypt a file with default algorithm and embedded initial vector.

require 'iop/file'
require 'iop/openssl'
( IOP::FileReader.new('input.aes') | IOP::CipherDecryptor.new(key: my_secret_key) | (s = IOP::StringMerger.new) ).process!
puts s.to_s

Since:

  • 0.1

Instance Attribute Summary collapse

Attributes included from Sink

#upstream

Attributes included from Feed

#downstream

Instance Method Summary collapse

Methods included from Sink

#process!

Methods included from Feed

#process!, #|

Constructor Details

#initialize(cipher = DEFAULT_OPENSSL_CIPHER, key:, iv: nil) ⇒ CipherDecryptor

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 iv is nil, the initial vector will be obtained from the upstream data. Refer to IOP::CipherEncryptor#initialize for details.

Parameters:

  • cipher (String, OpenSSL::Cipher) (defaults to: DEFAULT_OPENSSL_CIPHER)

    cipher used for decryption

  • key (String)

    string representing an encryption key

  • iv (String) (defaults to: nil)

    string representing an initial vector or nil

Since:

  • 0.1



120
121
122
123
124
125
# File 'lib/iop/openssl.rb', line 120

def initialize(cipher = DEFAULT_OPENSSL_CIPHER, key:, iv: nil)
  @cipher = cipher.is_a?(String) ? OpenSSL::Cipher.new(cipher) : cipher
  @cipher.decrypt
  @cipher.key = @key = key
  @cipher.iv = @iv = iv unless iv.nil?
end

Instance Attribute Details

#ivObject (readonly)

Returns initial vector (IV) for decryption session.

Since:

  • 0.1



103
104
105
# File 'lib/iop/openssl.rb', line 103

def iv
  @iv
end

#keyObject (readonly)

Returns decryption key.

Since:

  • 0.1



106
107
108
# File 'lib/iop/openssl.rb', line 106

def key
  @key
end

Instance Method Details

#process(data = nil) ⇒ Object

Since:

  • 0.1



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/iop/openssl.rb', line 127

def process(data = nil)
  unless @continue
    @continue = true
    @buffer = IOP.allocate_string(data.size)
    if iv.nil?
      @cipher.iv = @iv = data[0, @cipher.iv_len]
      data = data[@cipher.iv_len..-1]
    end
  end
  if data.nil?
    super(@cipher.final)
    super
  else
    super(@cipher.update(data, @buffer)) unless data.size.zero?
  end
end