Class: HPKE::HKDF

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/hpke/hkdf.rb

Direct Known Subclasses

HMAC_SHA256, HMAC_SHA384, HMAC_SHA512

Defined Under Namespace

Classes: HMAC_SHA256, HMAC_SHA384, HMAC_SHA512

Constant Summary collapse

ALGORITHMS =
{
  sha256: {
    name: 'SHA256',
    kdf_id: 1
  },
  sha384: {
    name: 'SHA384',
    kdf_id: 2
  },
  sha512: {
    name: 'SHA512',
    kdf_id: 3
  }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

#i2osp, #os2ip, #xor

Constructor Details

#initialize(alg_name) ⇒ HKDF



28
29
30
31
32
33
34
35
# File 'lib/hpke/hkdf.rb', line 28

def initialize(alg_name)
  if algorithm = ALGORITHMS[alg_name]
    @digest = OpenSSL::Digest.new(algorithm[:name])
    @kdf_id = algorithm[:kdf_id]
  else
    raise Exception.new('Unknown hash algorithm')
  end
end

Instance Attribute Details

#kdf_idObject (readonly)

Returns the value of attribute kdf_id.



7
8
9
# File 'lib/hpke/hkdf.rb', line 7

def kdf_id
  @kdf_id
end

Instance Method Details

#expand(prk, info, len) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/hpke/hkdf.rb', line 45

def expand(prk, info, len)
  n = (len.to_f / @digest.digest_length).ceil
  t = ['']
  for i in 0..n do
    t << hmac(prk, t[i] + info + (i + 1).chr)
  end
  t_concat = t.join
  t_concat[0..(len - 1)]
end

#extract(salt, ikm) ⇒ Object



41
42
43
# File 'lib/hpke/hkdf.rb', line 41

def extract(salt, ikm)
  hmac(salt, ikm)
end

#hmac(key, data) ⇒ Object



37
38
39
# File 'lib/hpke/hkdf.rb', line 37

def hmac(key, data)
  OpenSSL::HMAC.digest(@digest, key, data)
end

#labeled_expand(prk, label, info, l, suite_id) ⇒ Object



60
61
62
63
# File 'lib/hpke/hkdf.rb', line 60

def labeled_expand(prk, label, info, l, suite_id)
  labeled_info = i2osp(l, 2) + 'HPKE-v1' + suite_id + label + info
  expand(prk, labeled_info, l)
end

#labeled_extract(salt, label, ikm, suite_id) ⇒ Object



55
56
57
58
# File 'lib/hpke/hkdf.rb', line 55

def labeled_extract(salt, label, ikm, suite_id)
  labeled_ikm = 'HPKE-v1' + suite_id + label + ikm
  extract(salt, labeled_ikm)
end

#n_hObject



24
25
26
# File 'lib/hpke/hkdf.rb', line 24

def n_h
  @digest.digest_length
end