Module: Rex::Crypto::KeyDerivation::NIST_SP_800_108

Defined in:
lib/rex/crypto/key_derivation/nist_sp_800_108.rb

Class Method Summary collapse

Class Method Details

.counter(length, prf, keys: 1, label: ''.b, context: ''.b) ⇒ Array<String>

Generates key material using the NIST SP 800-108 R1 counter mode KDF.

Parameters:

  • length (Integer)

    The desired output length of each key in bytes.

  • prf (Proc)

    The pseudorandom function used for key derivation.

  • keys (Integer) (defaults to: 1)

    The number of derived keys to generate.

  • label (String) (defaults to: ''.b)

    Optional label to distinguish different derivations.

  • context (String) (defaults to: ''.b)

    Optional context to bind the key derivation to specific information.

Returns:

  • (Array<String>)

    An array of derived keys as binary strings, regardless of the number requested.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rex/crypto/key_derivation/nist_sp_800_108.rb', line 14

def self.counter(length, prf, keys: 1, label: ''.b, context: ''.b)
  key_block = ''

  counter = 0
  while key_block.length < (length * keys)
    counter += 1
    raise RangeError.new("counter overflow") if counter > 0xffffffff

    info = [ counter ].pack('L>') + label + "\x00".b + context + [ length * keys * 8 ].pack('L>')
    key_block << prf.call(info)
  end

  key_block.bytes.each_slice(length).to_a[...keys].map { |slice| slice.pack('C*') }
end

.counter_hmac(secret, length, algorithm, keys: 1, label: ''.b, context: ''.b) ⇒ Array<String>

Generates key material using the NIST SP 800-108 R1 counter mode KDF with HMAC.

Parameters:

  • secret (String)

    The secret key used as the HMAC key.

  • length (Integer)

    The desired output length of each key in bytes.

  • algorithm (String, Symbol)

    The HMAC hash algorithm (e.g., ‘SHA256`, `SHA512`).

  • keys (Integer) (defaults to: 1)

    The number of derived keys to generate (default: 1).

  • label (String) (defaults to: ''.b)

    Optional label to distinguish different derivations.

  • context (String) (defaults to: ''.b)

    Optional context to bind the key derivation to specific information.

Returns:

  • (Array<String>)

    Returns an array of derived keys.

Raises:

  • (ArgumentError)

    If the requested length is invalid or the algorithm is unsupported.



41
42
43
44
# File 'lib/rex/crypto/key_derivation/nist_sp_800_108.rb', line 41

def self.counter_hmac(secret, length, algorithm, keys: 1, label: ''.b, context: ''.b)
  prf = -> (data) { OpenSSL::HMAC.digest(algorithm, secret, data) }
  counter(length, prf, keys: keys, label: label, context: context)
end