Class: HPKE::DHKEM::EC

Inherits:
HPKE::DHKEM show all
Defined in:
lib/hpke/dhkem.rb

Direct Known Subclasses

P_256, P_384, P_521

Defined Under Namespace

Classes: P_256, P_384, P_521

Instance Method Summary collapse

Methods inherited from HPKE::DHKEM

#auth_decap, #auth_encap, #auth_encap_fixed, #decap, #encap, #encap_fixed, #generate_key_pair, #initialize

Methods included from Util

#i2osp, #os2ip, #xor

Constructor Details

This class inherits a constructor from HPKE::DHKEM

Instance Method Details

#create_key_pair_from_secret(secret) ⇒ Object



155
156
157
158
159
160
161
162
163
# File 'lib/hpke/dhkem.rb', line 155

def create_key_pair_from_secret(secret)
  asn1_seq = OpenSSL::ASN1.Sequence([
    OpenSSL::ASN1.Integer(1),
    OpenSSL::ASN1.OctetString(secret),
    OpenSSL::ASN1.ObjectId(curve_name, 0, :EXPLICIT)
  ])

  OpenSSL::PKey.read(asn1_seq.to_der)
end

#derive_key_pair(ikm) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/hpke/dhkem.rb', line 139

def derive_key_pair(ikm)
  dkp_prk = @hkdf.labeled_extract('', 'dkp_prk', ikm, kem_suite_id)
  sk = 0
  counter = 0
  while sk == 0 || sk >= order do
    raise Exception.new('DeriveKeyPairError') if counter > 255

    bytes = @hkdf.labeled_expand(dkp_prk, 'candidate', i2osp(counter, 1), n_sk, kem_suite_id)
    bytes[0] = (bytes[0].ord & bitmask).chr
    sk = os2ip(bytes)
    counter += 1
  end

  create_key_pair_from_secret(bytes)
end

#deserialize_public_key(serialized_pk) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
# File 'lib/hpke/dhkem.rb', line 169

def deserialize_public_key(serialized_pk)
  asn1_seq = OpenSSL::ASN1.Sequence([
    OpenSSL::ASN1.Sequence([
      OpenSSL::ASN1.ObjectId("id-ecPublicKey"),
      OpenSSL::ASN1.ObjectId(curve_name)
    ]),
    OpenSSL::ASN1.BitString(serialized_pk)
  ])

  OpenSSL::PKey.read(asn1_seq.to_der)
end

#serialize_public_key(pk) ⇒ Object



165
166
167
# File 'lib/hpke/dhkem.rb', line 165

def serialize_public_key(pk)
  pk.public_key.to_bn.to_s(2)
end