Class: RubyHome::HAP::Decrypter

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_home/hap/decrypter.rb

Constant Summary collapse

AAD_LENGTH_BYTES =
2.freeze
AUTHENTICATE_TAG_LENGTH_BYTES =
16.freeze
NONCE_32_BIT_FIX_COMMENT_PART =
[0].pack('L').freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, count: 0) ⇒ Decrypter

Returns a new instance of Decrypter.



8
9
10
11
# File 'lib/ruby_home/hap/decrypter.rb', line 8

def initialize(key, count: 0)
  @key = key
  @count = count
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



38
39
40
# File 'lib/ruby_home/hap/decrypter.rb', line 38

def count
  @count
end

Instance Method Details

#decrypt(data) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ruby_home/hap/decrypter.rb', line 13

def decrypt(data)
  decrypted_data = []
  read_pointer = 0

  while read_pointer < data.length
    little_endian_length_of_encrypted_data = data[read_pointer...read_pointer+AAD_LENGTH_BYTES]
    length_of_encrypted_data = little_endian_length_of_encrypted_data.unpack1('v')
    read_pointer += AAD_LENGTH_BYTES

    message = data[read_pointer...read_pointer+length_of_encrypted_data]
    read_pointer += length_of_encrypted_data

    auth_tag = data[read_pointer...read_pointer+AUTHENTICATE_TAG_LENGTH_BYTES]
    read_pointer += AUTHENTICATE_TAG_LENGTH_BYTES

    ciphertext = message + auth_tag
    additional_data = little_endian_length_of_encrypted_data
    decrypted_data << chacha20poly1305ietf.decrypt(nonce, ciphertext, additional_data)

    increment_count!
  end

  decrypted_data.join
end