Class: E3DCMqtt::RSCP::Rijndael256::CBCEncryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/e3dc_mqtt/rscp/rijndael256.rb

Overview

Stateful CBC encryption: each call to ‘update` chains from the previous ciphertext, mimicking Go’s ‘cipher.BlockMode`.

Instance Method Summary collapse

Constructor Details

#initialize(key, iv) ⇒ CBCEncryptor

Returns a new instance of CBCEncryptor.

Raises:

  • (ArgumentError)


201
202
203
204
205
206
# File 'lib/e3dc_mqtt/rscp/rijndael256.rb', line 201

def initialize(key, iv)
  raise ArgumentError, "IV must be #{BLOCK_SIZE} bytes" if iv.bytesize != BLOCK_SIZE

  @cipher = Cipher.new(key)
  @iv = iv.dup.force_encoding(Encoding::BINARY)
end

Instance Method Details

#update(plaintext) ⇒ Object

Raises:

  • (ArgumentError)


208
209
210
211
212
213
214
215
216
217
218
# File 'lib/e3dc_mqtt/rscp/rijndael256.rb', line 208

def update(plaintext)
  raise ArgumentError, "plaintext must be a multiple of #{BLOCK_SIZE} bytes" unless (plaintext.bytesize % BLOCK_SIZE).zero?

  out = String.new(capacity: plaintext.bytesize, encoding: Encoding::BINARY)
  (0...plaintext.bytesize).step(BLOCK_SIZE) do |i|
    block = Rijndael256.xor_bytes(plaintext.byteslice(i, BLOCK_SIZE), @iv)
    @iv = @cipher.encrypt_block(block)
    out << @iv
  end
  out
end