Class: PqcRails::DhKem

Inherits:
Object
  • Object
show all
Includes:
LengthValidation
Defined in:
lib/pqc_rails/dh_kem.rb

Overview

古典的なECDH(X25519)を「KEM」のAPI形状(generate_keypair/encapsulate/decapsulate)で 包んだクラス。RFC 9180(HPKE)のDHKEMと同じ考え方:

encapsulate: 

これにより PqcRails::Kem (liboqs) と同じインターフェースで古典鍵を扱えるようになり、 HybridKem側で両者を対称に組み合わせられる。

使い方:

dh_kem = PqcRails::DhKem.new
keypair = dh_kem.generate_keypair
encap   = dh_kem.encapsulate(keypair.public_key)
shared  = dh_kem.decapsulate(encap.ciphertext, keypair.secret_key)
shared == encap.shared_secret # => true

Defined Under Namespace

Classes: Encapsulation, Keypair

Constant Summary collapse

KEY_LENGTH =
32

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(curve = "X25519") ⇒ DhKem

Returns a new instance of DhKem.



33
34
35
# File 'lib/pqc_rails/dh_kem.rb', line 33

def initialize(curve = "X25519")
  @curve = curve
end

Instance Attribute Details

#curveObject (readonly)

Returns the value of attribute curve.



31
32
33
# File 'lib/pqc_rails/dh_kem.rb', line 31

def curve
  @curve
end

Instance Method Details

#decapsulate(ciphertext, secret_key) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/pqc_rails/dh_kem.rb', line 56

def decapsulate(ciphertext, secret_key)
  validate_length!(ciphertext, length_ciphertext, "ciphertext")
  validate_length!(secret_key, length_secret_key, "secret_key")

  own_key       = OpenSSL::PKey.new_raw_private_key(@curve, secret_key)
  ephemeral_pub = OpenSSL::PKey.new_raw_public_key(@curve, ciphertext)

  own_key.derive(ephemeral_pub)
end

#encapsulate(public_key) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/pqc_rails/dh_kem.rb', line 47

def encapsulate(public_key)
  validate_length!(public_key, length_public_key, "public_key")

  peer_key  = OpenSSL::PKey.new_raw_public_key(@curve, public_key)
  ephemeral = OpenSSL::PKey.generate_key(@curve)

  Encapsulation.new(ephemeral.raw_public_key, ephemeral.derive(peer_key))
end

#generate_keypairObject



42
43
44
45
# File 'lib/pqc_rails/dh_kem.rb', line 42

def generate_keypair
  key = OpenSSL::PKey.generate_key(@curve)
  Keypair.new(key.raw_public_key, key.raw_private_key)
end

#length_ciphertextObject



39
# File 'lib/pqc_rails/dh_kem.rb', line 39

def length_ciphertext    = KEY_LENGTH

#length_public_keyObject



37
# File 'lib/pqc_rails/dh_kem.rb', line 37

def length_public_key    = KEY_LENGTH

#length_secret_keyObject



38
# File 'lib/pqc_rails/dh_kem.rb', line 38

def length_secret_key    = KEY_LENGTH

#length_shared_secretObject



40
# File 'lib/pqc_rails/dh_kem.rb', line 40

def length_shared_secret = KEY_LENGTH