Class: E3DCMqtt::RSCP::Rijndael256::Cipher

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

Overview

256-bit block cipher. Not thread-safe (instance mutates a scratch state during encrypt/decrypt), but round keys are immutable so multiple instances sharing a key work fine.

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Cipher

Returns a new instance of Cipher.

Raises:

  • (ArgumentError)


59
60
61
62
63
# File 'lib/e3dc_mqtt/rscp/rijndael256.rb', line 59

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

  @round_keys = expand_key(key)
end

Instance Method Details

#decrypt_block(src) ⇒ Object

Raises:

  • (ArgumentError)


84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/e3dc_mqtt/rscp/rijndael256.rb', line 84

def decrypt_block(src)
  raise ArgumentError, "block must be #{BLOCK_SIZE} bytes" if src.bytesize != BLOCK_SIZE

  state = src.bytes
  add_key(state, @round_keys, BLOCK_WORDS * ROUNDS)
  inv_shift_rows(state)
  state.map! { |b| SBOX_INV[b] }

  (ROUNDS - 1).downto(1) do |round|
    add_key(state, @round_keys, BLOCK_WORDS * round)
    inv_mix_columns(state)
    inv_shift_rows(state)
    state.map! { |b| SBOX_INV[b] }
  end

  add_key(state, @round_keys, 0)
  state.pack("C*")
end

#encrypt_block(src) ⇒ Object

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/e3dc_mqtt/rscp/rijndael256.rb', line 65

def encrypt_block(src)
  raise ArgumentError, "block must be #{BLOCK_SIZE} bytes" if src.bytesize != BLOCK_SIZE

  state = src.bytes
  add_key(state, @round_keys, 0)

  (1...ROUNDS).each do |round|
    state.map! { |b| SBOX[b] }
    shift_rows(state)
    mix_columns(state)
    add_key(state, @round_keys, BLOCK_WORDS * round)
  end

  state.map! { |b| SBOX[b] }
  shift_rows(state)
  add_key(state, @round_keys, BLOCK_WORDS * ROUNDS)
  state.pack("C*")
end