Class: Noise::State::CipherState

Inherits:
Object
  • Object
show all
Defined in:
lib/noise/state/cipher_state.rb

Overview

A CipherState can encrypt and decrypt data based on its k and n variables:

  • k: A cipher key of 32 bytes (which may be empty). Empty is a special value which indicates k has not yet been

initialized.

  • n: An 8-byte (64-bit) unsigned integer nonce.

Constant Summary collapse

MAX_NONCE =
2**64 - 1

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cipher: AesGcm.new) ⇒ CipherState

Returns a new instance of CipherState.



16
17
18
# File 'lib/noise/state/cipher_state.rb', line 16

def initialize(cipher: AesGcm.new)
  @cipher = cipher
end

Instance Attribute Details

#kObject (readonly)

Returns the value of attribute k.



14
15
16
# File 'lib/noise/state/cipher_state.rb', line 14

def k
  @k
end

#nObject (readonly)

Returns the value of attribute n.



14
15
16
# File 'lib/noise/state/cipher_state.rb', line 14

def n
  @n
end

Instance Method Details

#decrypt_with_ad(ad, ciphertext) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/noise/state/cipher_state.rb', line 45

def decrypt_with_ad(ad, ciphertext)
  return ciphertext unless key?
  raise Noise::Exceptions::MaxNonceError if @n == MAX_NONCE
  plaintext = @cipher.decrypt(@k, @n, ad, ciphertext)
  @n += 1
  plaintext
end

#encrypt_with_ad(ad, plaintext) ⇒ Object

@return [String] ENCRYPT(k, n++, ad, plaintext) if k is non-empty, otherwise returns plaintext.



36
37
38
39
40
41
42
# File 'lib/noise/state/cipher_state.rb', line 36

def encrypt_with_ad(ad, plaintext)
  return plaintext unless key?
  raise Noise::Exceptions::MaxNonceError if @n == MAX_NONCE
  ciphertext = @cipher.encrypt(@k, @n, ad, plaintext)
  @n += 1
  ciphertext
end

#initialize_key(key) ⇒ Object

Parameters:



21
22
23
24
# File 'lib/noise/state/cipher_state.rb', line 21

def initialize_key(key)
  @k = key
  @n = 0
end

#key?Boolean

Returns true if k is non-empty, false otherwise.

Returns:

  • (Boolean)

    true if k is non-empty, false otherwise.



27
28
29
# File 'lib/noise/state/cipher_state.rb', line 27

def key?
  !@k.nil?
end

#nonce=(nonce) ⇒ Object



31
32
33
# File 'lib/noise/state/cipher_state.rb', line 31

def nonce=(nonce)
  @n = nonce
end

#rekeyObject



53
54
55
# File 'lib/noise/state/cipher_state.rb', line 53

def rekey
  @k = @cipher.rekey(@k)
end