pqc_rails 0.4.0-x86_64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +379 -0
  3. data/LICENSE.txt +202 -0
  4. data/NOTICE.md +73 -0
  5. data/README.md +478 -0
  6. data/Rakefile +18 -0
  7. data/docs/CRYPTO_INVENTORY.md +49 -0
  8. data/docs/MIGRATION.md +211 -0
  9. data/docs/THREAT_MODEL.md +188 -0
  10. data/gemfiles/rails_7.1.gemfile +14 -0
  11. data/gemfiles/rails_8.1.gemfile +14 -0
  12. data/lib/pqc_rails/active_record/ciphertext_info.rb +48 -0
  13. data/lib/pqc_rails/active_record/context.rb +44 -0
  14. data/lib/pqc_rails/active_record/key_provider.rb +97 -0
  15. data/lib/pqc_rails/algorithms.rb +74 -0
  16. data/lib/pqc_rails/blob_packing.rb +73 -0
  17. data/lib/pqc_rails/cipher.rb +167 -0
  18. data/lib/pqc_rails/ciphertext_format.rb +163 -0
  19. data/lib/pqc_rails/configuration.rb +123 -0
  20. data/lib/pqc_rails/dh_kem.rb +71 -0
  21. data/lib/pqc_rails/envelope_cipher.rb +78 -0
  22. data/lib/pqc_rails/ffi/kem.rb +43 -0
  23. data/lib/pqc_rails/ffi/sig.rb +68 -0
  24. data/lib/pqc_rails/generators/install/install_generator.rb +48 -0
  25. data/lib/pqc_rails/generators/install/templates/initializer.rb +10 -0
  26. data/lib/pqc_rails/hybrid_kem.rb +144 -0
  27. data/lib/pqc_rails/kem.rb +130 -0
  28. data/lib/pqc_rails/key_source.rb +146 -0
  29. data/lib/pqc_rails/length_validation.rb +22 -0
  30. data/lib/pqc_rails/native/liboqs.so +0 -0
  31. data/lib/pqc_rails/railtie.rb +12 -0
  32. data/lib/pqc_rails/redacted_struct.rb +53 -0
  33. data/lib/pqc_rails/secret_buffer.rb +35 -0
  34. data/lib/pqc_rails/session/encryptor.rb +141 -0
  35. data/lib/pqc_rails/session/key_manager.rb +40 -0
  36. data/lib/pqc_rails/session/pqc_cookie_store.rb +60 -0
  37. data/lib/pqc_rails/sig.rb +165 -0
  38. data/lib/pqc_rails/status_check.rb +240 -0
  39. data/lib/pqc_rails/tasks/pqc_rails.rake +16 -0
  40. data/lib/pqc_rails/version.rb +5 -0
  41. data/lib/pqc_rails.rb +41 -0
  42. data/sig/pqc_rails.rbs +4 -0
  43. metadata +176 -0
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PqcRails
4
+ # gem全体の設定。Railsアプリ側からは以下のように使う想定:
5
+ #
6
+ # # config/initializers/pqc_rails.rb
7
+ # PqcRails.configure do |config|
8
+ # config.liboqs_path = "/usr/local/lib/liboqs.dylib"
9
+ # end
10
+ class Configuration
11
+ # プラットフォーム別のgem(x86_64-linux-gnu等)が、ビルド済みのliboqsを同梱する場所。
12
+ NATIVE_DIR = File.expand_path("native", __dir__)
13
+ # liboqsの共有ライブラリへのパス。
14
+ # 未設定の場合、環境変数 LIBOQS_PATH、それも無ければOS標準の場所を仮定する。
15
+ attr_accessor :liboqs_path
16
+
17
+ CIPHERTEXT_FORMATS = %i[v1 v0].freeze
18
+
19
+ # 暗号化時に書く暗号文の形式。復号は設定によらず両方の形式を読める。
20
+ # :v1 形式バージョン・アルゴリズムID・鍵IDを持つ形式(既定)
21
+ # :v0 0.3.0以前と同じ旧形式。複数台のサーバーへ順番にデプロイする間、まだ旧版のgemが動いている
22
+ # サーバーにも読める暗号文を書くために使う。全台の更新後に:v1へ戻す
23
+ attr_reader :ciphertext_format
24
+
25
+ # 旧形式(v0)の暗号文は作成元の認証を持たず、公開鍵だけで正しく復号できる暗号文を作れる。
26
+ # 旧形式のデータが残っていない状態になったら、旧形式を受け付けないようにする。
27
+
28
+ # 旧形式のDBカラムを復号するかどうか(既定はtrue)。全レコードを再暗号化した後にfalseにする。
29
+ attr_reader :accept_legacy_records
30
+
31
+ # 認証鍵を持たない鍵(0.3.0以前に生成した鍵)宛の旧形式のセッションCookieを、この日時まで復号する。
32
+ # 既定のnilでは復号しない。ciphertext_formatが:v0の間は、順番デプロイ中のCookieを読むため期限によらず復号する。
33
+ # 旧形式のCookieは発行日時を持たないため、旧形式の発行が止まる日時に最長のセッション有効期限を足した日時を設定する。
34
+ attr_reader :accept_legacy_cookies_until
35
+
36
+ def initialize
37
+ @liboqs_path = ENV["LIBOQS_PATH"] || default_liboqs_path
38
+ @ciphertext_format = :v1
39
+ @accept_legacy_records = true
40
+ @accept_legacy_cookies_until = nil
41
+ end
42
+
43
+ def ciphertext_format=(format)
44
+ unless CIPHERTEXT_FORMATS.include?(format)
45
+ raise ArgumentError, "ciphertext_format must be one of #{CIPHERTEXT_FORMATS.inspect}, got #{format.inspect}"
46
+ end
47
+
48
+ @ciphertext_format = format
49
+ end
50
+
51
+ def accept_legacy_records=(value)
52
+ unless [true, false].include?(value)
53
+ raise ArgumentError, "accept_legacy_records must be true or false, got #{value.inspect}"
54
+ end
55
+
56
+ @accept_legacy_records = value
57
+ end
58
+
59
+ def accept_legacy_cookies_until=(time)
60
+ unless time.nil? || time.is_a?(Time)
61
+ raise ArgumentError, "accept_legacy_cookies_until must be a Time or nil, got #{time.inspect}"
62
+ end
63
+
64
+ @accept_legacy_cookies_until = time
65
+ end
66
+
67
+ private
68
+
69
+ # liboqsのデフォルトパス。
70
+ # プラットフォーム別のgemが同梱したビルド済みのliboqs、次にbundle install時に
71
+ # ext/pqc_rails/extconf.rbが自前でビルドしたliboqsの順に探す。
72
+ # 見つからない場合はOS別の「よくあるインストール場所」を当て推量するが、
73
+ # 本番運用では明示的に liboqs_path を設定することを強く推奨する。
74
+ def default_liboqs_path
75
+ native_liboqs_path || bundled_liboqs_path || os_default_liboqs_path
76
+ end
77
+
78
+ # プラットフォーム別のgemが同梱したビルド済みのliboqsがあれば、そのパスを返す。
79
+ # ソースのgem(platform: ruby)には含まれないので、その場合はnilを返す。
80
+ def native_liboqs_path
81
+ %w[liboqs.dylib liboqs.so].map { |name| File.join(NATIVE_DIR, name) }.find { |path| File.exist?(path) }
82
+ end
83
+
84
+ # gemのインストールディレクトリ配下、ext/pqc_rails/extconf.rbがビルド後にコピーした
85
+ # 共有ライブラリがあれば、そのパスを返す(gem_dir、Gem::Specification#extension_dirでは
86
+ # ない点に注意。extconf.rbはビルド成果物を自身のカレントディレクトリ=ext/pqc_rails/へ
87
+ # コピーしており、RubyGemsが`make install`経由でextension_dirへ配置する仕組みには
88
+ # 乗せていないため)。gemとしてインストールされていない場合(このリポジトリを直接bundle
89
+ # pathで使う開発時等)はnilを返し、呼び出し元がOS標準パスへフォールバックする。
90
+ def bundled_liboqs_path
91
+ spec = Gem.loaded_specs["pqc_rails"]
92
+ return nil unless spec
93
+
94
+ %w[liboqs.dylib liboqs.so].map { |name| File.join(spec.gem_dir, "ext", "pqc_rails", name) }
95
+ .find { |path| File.exist?(path) }
96
+ rescue Gem::Exception
97
+ nil
98
+ end
99
+
100
+ def os_default_liboqs_path
101
+ case RbConfig::CONFIG["host_os"]
102
+ when /darwin/
103
+ "/usr/local/lib/liboqs.dylib"
104
+ when /linux/
105
+ "/usr/local/lib/liboqs.so"
106
+ else
107
+ raise PqcRails::Error,
108
+ "liboqs_path is not set and no default is known for this OS (#{RbConfig::CONFIG['host_os']}). " \
109
+ "Set PqcRails.configure { |c| c.liboqs_path = '...' } explicitly."
110
+ end
111
+ end
112
+ end
113
+
114
+ class << self
115
+ def configuration
116
+ @configuration ||= Configuration.new
117
+ end
118
+
119
+ def configure
120
+ yield(configuration)
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require_relative "length_validation"
5
+ require_relative "redacted_struct"
6
+
7
+ module PqcRails
8
+ # 古典的なECDH(X25519)を「KEM」のAPI形状(generate_keypair/encapsulate/decapsulate)で
9
+ # 包んだクラス。RFC 9180(HPKE)のDHKEMと同じ考え方:
10
+ #
11
+ # encapsulate: 一時鍵ペアを生成し、一時秘密鍵と相手の公開鍵からECDHで共有鍵を導出する。
12
+ # ciphertextは一時鍵の公開鍵そのもの。
13
+ # decapsulate: 自分の秘密鍵とciphertext(相手の一時公開鍵)からECDHで同じ共有鍵を導出する。
14
+ #
15
+ # これにより PqcRails::Kem (liboqs) と同じインターフェースで古典鍵を扱えるようになり、
16
+ # HybridKem側で両者を対称に組み合わせられる。
17
+ #
18
+ # 使い方:
19
+ # dh_kem = PqcRails::DhKem.new
20
+ # keypair = dh_kem.generate_keypair
21
+ # encap = dh_kem.encapsulate(keypair.public_key)
22
+ # shared = dh_kem.decapsulate(encap.ciphertext, keypair.secret_key)
23
+ # shared == encap.shared_secret # => true
24
+ class DhKem
25
+ include LengthValidation
26
+
27
+ Keypair = Struct.new(:public_key, :secret_key) do
28
+ include RedactedStruct
29
+ end
30
+ Encapsulation = Struct.new(:ciphertext, :shared_secret) do
31
+ include RedactedStruct
32
+ end
33
+
34
+ KEY_LENGTH = 32
35
+
36
+ attr_reader :curve
37
+
38
+ def initialize(curve = "X25519")
39
+ @curve = curve
40
+ end
41
+
42
+ def length_public_key = KEY_LENGTH
43
+ def length_secret_key = KEY_LENGTH
44
+ def length_ciphertext = KEY_LENGTH
45
+ def length_shared_secret = KEY_LENGTH
46
+
47
+ def generate_keypair
48
+ key = OpenSSL::PKey.generate_key(@curve)
49
+ Keypair.new(key.raw_public_key, key.raw_private_key)
50
+ end
51
+
52
+ def encapsulate(public_key)
53
+ validate_length!(public_key, length_public_key, "public_key")
54
+
55
+ peer_key = OpenSSL::PKey.new_raw_public_key(@curve, public_key)
56
+ ephemeral = OpenSSL::PKey.generate_key(@curve)
57
+
58
+ Encapsulation.new(ephemeral.raw_public_key, ephemeral.derive(peer_key))
59
+ end
60
+
61
+ def decapsulate(ciphertext, secret_key)
62
+ validate_length!(ciphertext, length_ciphertext, "ciphertext")
63
+ validate_length!(secret_key, length_secret_key, "secret_key")
64
+
65
+ own_key = OpenSSL::PKey.new_raw_private_key(@curve, secret_key)
66
+ ephemeral_pub = OpenSSL::PKey.new_raw_public_key(@curve, ciphertext)
67
+
68
+ own_key.derive(ephemeral_pub)
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require_relative "length_validation"
5
+
6
+ module PqcRails
7
+ # AES-256-GCMによるエンベロープ暗号化。HybridKem等で導出した32バイトの共有鍵を使って
8
+ # 実際のデータ(平文)を暗号化/復号する。「鍵交換」と「データ暗号化」を分離するのは、
9
+ # 後でActiveRecord::Encryption統合で「鍵→暗号化結果」のインターフェースとして
10
+ # そのまま使えるようにするため。
11
+ #
12
+ # 暗号文のフォーマット: IV(12byte) + 認証タグ(16byte) + 暗号文本体
13
+ # この3つを1本のバイト列にまとめて返すことで、DBカラム等に1カラムでそのまま保存できる。
14
+ #
15
+ # 使い方:
16
+ # cipher = PqcRails::EnvelopeCipher.new(key) # 32バイトの鍵
17
+ # encrypted = cipher.encrypt("secret")
18
+ # cipher.decrypt(encrypted) # => "secret"
19
+ class EnvelopeCipher
20
+ include LengthValidation
21
+
22
+ CIPHER_NAME = "aes-256-gcm"
23
+ KEY_LENGTH = 32
24
+ IV_LENGTH = 12
25
+ TAG_LENGTH = 16
26
+
27
+ def initialize(key)
28
+ validate_length!(key, KEY_LENGTH, "key")
29
+ @key = key
30
+ end
31
+
32
+ def encrypt(plaintext, associated_data: nil)
33
+ cipher = OpenSSL::Cipher.new(CIPHER_NAME)
34
+ cipher.encrypt
35
+ cipher.key = @key
36
+ iv = cipher.random_iv
37
+ cipher.auth_data = associated_data if associated_data
38
+
39
+ ciphertext = cipher.update(plaintext) + cipher.final
40
+
41
+ iv + cipher.auth_tag + ciphertext
42
+ end
43
+
44
+ # IVと認証タグに満たない入力は、OpenSSLに短い認証タグを設定する前にArgumentErrorにする
45
+ # (GCMは短い認証タグでも検証を行うため、タグの長さはここで保証する)。
46
+ def decrypt(encrypted, associated_data: nil)
47
+ validate_string!(encrypted, "encrypted")
48
+ if encrypted.bytesize < IV_LENGTH + TAG_LENGTH
49
+ raise ArgumentError,
50
+ "encrypted is too short: expected at least #{IV_LENGTH + TAG_LENGTH} bytes, got #{encrypted.bytesize}"
51
+ end
52
+
53
+ iv = encrypted[0, IV_LENGTH]
54
+ tag = encrypted[IV_LENGTH, TAG_LENGTH]
55
+ ciphertext = encrypted[(IV_LENGTH + TAG_LENGTH)..]
56
+
57
+ cipher = OpenSSL::Cipher.new(CIPHER_NAME)
58
+ cipher.decrypt
59
+ cipher.key = @key
60
+ cipher.iv = iv
61
+ cipher.auth_tag = tag
62
+ cipher.auth_data = associated_data if associated_data
63
+
64
+ cipher.update(ciphertext) + cipher.final
65
+ end
66
+
67
+ # 既定のinspect(ppも使う)・ActiveSupportのas_json・YAMLはインスタンス変数を出すため、鍵を伏せる。
68
+ def inspect = "#<#{self.class.name} key=[FILTERED]>"
69
+
70
+ def as_json(_options = nil) = { "key" => "[FILTERED]" }
71
+
72
+ # YAMLも同じ内容のタグ無しのマップにする。読み戻してもEnvelopeCipherにはならない。
73
+ def encode_with(coder)
74
+ coder.represent_map(nil, as_json)
75
+ coder.implicit = true
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module PqcRails
6
+ module Ffi
7
+ # liboqsのGeneric KEM APIへの低レベルFFIバインディング。
8
+ module Kem
9
+ extend FFI::Library
10
+
11
+ ffi_lib PqcRails.configuration.liboqs_path
12
+
13
+ class Struct < FFI::Struct
14
+ layout(
15
+ :method_name, :pointer,
16
+ :alg_version, :pointer,
17
+ :claimed_nist_level, :uint8,
18
+ :ind_cca, :bool,
19
+ :length_public_key, :size_t,
20
+ :length_secret_key, :size_t,
21
+ :length_ciphertext, :size_t,
22
+ :length_shared_secret, :size_t,
23
+ :length_keypair_seed, :size_t,
24
+ :length_encaps_seed, :size_t,
25
+ :keypair_derand, :pointer,
26
+ :keypair, :pointer,
27
+ :encaps_derand, :pointer,
28
+ :encaps, :pointer,
29
+ :decaps, :pointer
30
+ )
31
+ end
32
+
33
+ attach_function :OQS_KEM_new, [:string], :pointer
34
+ attach_function :OQS_KEM_free, [:pointer], :void
35
+ attach_function :OQS_KEM_keypair, [:pointer, :pointer, :pointer], :int
36
+ attach_function :OQS_KEM_encaps, [:pointer, :pointer, :pointer, :pointer], :int
37
+ attach_function :OQS_KEM_decaps, [:pointer, :pointer, :pointer, :pointer], :int
38
+
39
+ # liboqs/include/oqs/common.h の const char *OQS_version(void)。読み込んだliboqsの版を返す。
40
+ attach_function :OQS_version, [], :string
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module PqcRails
6
+ module Ffi
7
+ # liboqsのGeneric SIG(署名)APIへの低レベルFFIバインディング。
8
+ # PqcRails::Ffi::Kem と対になる、署名アルゴリズム版。
9
+ module Sig
10
+ extend FFI::Library
11
+
12
+ ffi_lib PqcRails.configuration.liboqs_path
13
+
14
+ # liboqs/include/oqs/sig.h の OQS_SIG 構造体に対応するフィールド順序です(liboqs 0.15.0/0.16.0時点、
15
+ # 両バージョンでフィールド順序に変更はありません)。
16
+ #
17
+ # KEMのOQS_KEM構造体との違い:
18
+ # - euf_cma / suf_cma / sig_with_ctx_support という3つのbool値が追加されている
19
+ # - length_ciphertext / length_shared_secret は無く、代わりに length_signature がある
20
+ # - keypair_derand に相当するderandomized版は無い(liboqs 0.15.0/0.16.0いずれのヘッダにも存在しない)
21
+ # - sign / verify に加えて、コンテキスト文字列付きの
22
+ # sign_with_ctx_str / verify_with_ctx_str が追加で存在する
23
+ class Struct < FFI::Struct
24
+ layout(
25
+ :method_name, :pointer,
26
+ :alg_version, :pointer,
27
+ :claimed_nist_level, :uint8,
28
+ :euf_cma, :bool,
29
+ :suf_cma, :bool,
30
+ :sig_with_ctx_support, :bool,
31
+ :length_public_key, :size_t,
32
+ :length_secret_key, :size_t,
33
+ :length_signature, :size_t,
34
+ :keypair, :pointer,
35
+ :sign, :pointer,
36
+ :sign_with_ctx_str, :pointer,
37
+ :verify, :pointer,
38
+ :verify_with_ctx_str, :pointer
39
+ )
40
+ end
41
+
42
+ # OQS_SIG *OQS_SIG_new(const char *method_name);
43
+ attach_function :OQS_SIG_new, [:string], :pointer
44
+
45
+ # void OQS_SIG_free(OQS_SIG *sig);
46
+ attach_function :OQS_SIG_free, [:pointer], :void
47
+
48
+ # OQS_STATUS OQS_SIG_keypair(const OQS_SIG *sig, uint8_t *public_key, uint8_t *secret_key);
49
+ attach_function :OQS_SIG_keypair, [:pointer, :pointer, :pointer], :int
50
+
51
+ # OQS_STATUS OQS_SIG_sign(const OQS_SIG *sig, uint8_t *signature, size_t *signature_len,
52
+ # const uint8_t *message, size_t message_len, const uint8_t *secret_key);
53
+ # 引数は6個: sig, signature, signature_len(出力, size_t*), message, message_len, secret_key
54
+ # signature_len は size_t* (出力引数)。FFIでは :pointer として渡し、
55
+ # 呼び出し側で FFI::MemoryPointer#read(:size_t) 等で読み出す必要がある。
56
+ attach_function :OQS_SIG_sign,
57
+ [:pointer, :pointer, :pointer, :pointer, :size_t, :pointer],
58
+ :int
59
+
60
+ # OQS_STATUS OQS_SIG_verify(const OQS_SIG *sig, const uint8_t *message, size_t message_len,
61
+ # const uint8_t *signature, size_t signature_len, const uint8_t *public_key);
62
+ # 引数は6個: sig, message, message_len, signature, signature_len, public_key
63
+ attach_function :OQS_SIG_verify,
64
+ [:pointer, :pointer, :size_t, :pointer, :size_t, :pointer],
65
+ :int
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "rails/generators"
5
+ require_relative "../../hybrid_kem"
6
+ require_relative "../../key_source"
7
+ require_relative "../../session/encryptor"
8
+
9
+ module PqcRails
10
+ module Generators
11
+ # `rails generate pqc_rails:install` で実行される。
12
+ # config/initializers/pqc_rails.rbを生成し、セッション暗号化用のHybridKemキーペアを
13
+ # 生成してRails credentialsに保存する。
14
+ class InstallGenerator < Rails::Generators::Base
15
+ source_root File.expand_path("templates", __dir__)
16
+
17
+ desc "Generates the pqc_rails initializer and a PQC session key in Rails credentials."
18
+
19
+ def create_initializer
20
+ copy_file "initializer.rb", "config/initializers/pqc_rails.rb"
21
+ end
22
+
23
+ def add_session_key_to_credentials
24
+ encoded_key = PqcRails::KeySource.encode(generated_keypair)
25
+
26
+ credentials.change do |tmp_path|
27
+ data = YAML.safe_load(tmp_path.read, permitted_classes: [Symbol], aliases: true) || {}
28
+ data["pqc_session_key"] = encoded_key
29
+ tmp_path.write(data.to_yaml)
30
+ end
31
+
32
+ say_status :credentials, "Added pqc_session_key to Rails credentials"
33
+ end
34
+
35
+ private
36
+
37
+ def generated_keypair
38
+ @generated_keypair ||= PqcRails::HybridKem.open(PqcRails::Session::Encryptor::DEFAULT_PQ_ALG_NAME) do |hybrid|
39
+ hybrid.generate_keypair
40
+ end
41
+ end
42
+
43
+ def credentials
44
+ Rails.application.credentials
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ # config/application.rb (または config/initializers/session_store.rb) で
4
+ # 以下を設定すると、セッションがPQC(ML-KEM + X25519のハイブリッド)で暗号化されます。
5
+ #
6
+ # config.session_store :pqc_cookie_store
7
+ #
8
+ PqcRails.configure do |config|
9
+ # config.liboqs_path = "/usr/local/lib/liboqs.dylib"
10
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require_relative "blob_packing"
5
+ require_relative "dh_kem"
6
+ require_relative "kem"
7
+ require_relative "secret_buffer"
8
+ require_relative "redacted_struct"
9
+
10
+ module PqcRails
11
+ # 古典ECDH(DhKem)とPQ KEM(liboqs経由のKem)を組み合わせたハイブリッドKEM。
12
+ #
13
+ # 量子コンピュータがPQ側を破ったとしても古典側が安全なら(あるいはその逆でも)
14
+ # 全体の共有鍵は安全、という「移行期間中の保険」を提供するのが目的。
15
+ # NIST標準化されたML-KEMはまだ実運用歴が浅いため、実績のあるX25519と組み合わせることで
16
+ # 「PQアルゴリズム自体に未知の脆弱性が見つかった場合」のリスクを下げる。
17
+ #
18
+ # コンバイナの方式: 古典側の共有鍵とPQ側の共有鍵を連結し、両者のciphertext
19
+ # (encapsulateの出力)をHKDFのinfoにバインドした上でHKDF-SHA256にかけて
20
+ # 32バイトの最終共有鍵を導出する。ciphertextをバインドするのは、
21
+ # 通常のTLSハンドシェイクのようなトランスクリプトハッシュによる結合が無い
22
+ # スタンドアロン用途のため、コンバイナ自体に結合の安全性を持たせる必要があるため。
23
+ #
24
+ # この「連結してからHKDFにかける」方式は自己流ではなく、RFC 9954(TLS 1.3ハイブリッド鍵共有、
25
+ # 旧draft-ietf-tls-hybrid-design)が採用する"concatenation approach"と同じ構成であり、
26
+ # NIST SP 800-56Cが承認済みアルゴリズムと非承認アルゴリズムのハイブリッド共有鍵生成における
27
+ # 承認済み手法として単純連結を挙げている。RFC 9954はこの構成が「dual-PRFコンバイナ」に対応し、
28
+ # ハッシュ関数がdual-PRFであるという仮定の下で安全性が証明されているとしている([BINDEL]論文)。
29
+ # なお、RFC 9370(IKEv2の複数鍵交換)はSKEYSEED(n) = prf(SK_d(n-1), SK(n) | Ni | Nr)という
30
+ # 逐次的なPRF連鎖(cascade)を採るため、本実装とは別のコンバイナ方式である点に注意。
31
+ #
32
+ # 使い方:
33
+ # PqcRails::HybridKem.open(:ml_kem_512) do |hybrid|
34
+ # keypair = hybrid.generate_keypair
35
+ # encap = hybrid.encapsulate(keypair.public_key)
36
+ # shared = hybrid.decapsulate(encap.ciphertext, keypair.secret_key)
37
+ # shared == encap.shared_secret # => true
38
+ # end
39
+ class HybridKem
40
+ # authentication_keyは、暗号文の作成元の認証に使う32バイトのランダムな共通鍵
41
+ # (CiphertextFormat.data_key参照)。KEMの演算には使わない。0.3.0以前に生成した鍵は持たない(nil)。
42
+ Keypair = Struct.new(:public_key, :secret_key, :authentication_key) do
43
+ include RedactedStruct
44
+ end
45
+ AUTHENTICATION_KEY_LENGTH = 32
46
+ Encapsulation = Struct.new(:ciphertext, :shared_secret) do
47
+ include RedactedStruct
48
+ end
49
+
50
+ COMBINER_LABEL = "pqc_rails-hybrid-kem-v1"
51
+ SHARED_SECRET_LENGTH = 32
52
+
53
+ attr_reader :pq_alg_name, :classical_curve
54
+
55
+ def initialize(pq_alg_name, classical_curve = "X25519")
56
+ @pq_alg_name = pq_alg_name
57
+ @classical_curve = classical_curve
58
+ @classical = DhKem.new(classical_curve)
59
+ @pq = Kem.new(pq_alg_name)
60
+ @freed = false
61
+ end
62
+
63
+ def generate_keypair
64
+ ensure_not_freed!
65
+
66
+ classical_keypair = @classical.generate_keypair
67
+ pq_keypair = @pq.generate_keypair
68
+
69
+ Keypair.new(
70
+ BlobPacking.pack(classical_keypair.public_key, pq_keypair.public_key),
71
+ BlobPacking.pack(classical_keypair.secret_key, pq_keypair.secret_key),
72
+ OpenSSL::Random.random_bytes(AUTHENTICATION_KEY_LENGTH)
73
+ )
74
+ end
75
+
76
+ def encapsulate(public_key)
77
+ ensure_not_freed!
78
+
79
+ classical_public_key, pq_public_key = BlobPacking.unpack(public_key, exact: true)
80
+ classical_encap = @classical.encapsulate(classical_public_key)
81
+ pq_encap = @pq.encapsulate(pq_public_key)
82
+
83
+ Encapsulation.new(
84
+ BlobPacking.pack(classical_encap.ciphertext, pq_encap.ciphertext),
85
+ combine(classical_encap.shared_secret, pq_encap.shared_secret,
86
+ classical_encap.ciphertext, pq_encap.ciphertext)
87
+ )
88
+ end
89
+
90
+ def decapsulate(ciphertext, secret_key)
91
+ ensure_not_freed!
92
+
93
+ classical_ciphertext, pq_ciphertext = BlobPacking.unpack(ciphertext, exact: true)
94
+ classical_secret_key, pq_secret_key = BlobPacking.unpack(secret_key)
95
+
96
+ classical_shared = @classical.decapsulate(classical_ciphertext, classical_secret_key)
97
+ pq_shared = @pq.decapsulate(pq_ciphertext, pq_secret_key)
98
+
99
+ combine(classical_shared, pq_shared, classical_ciphertext, pq_ciphertext)
100
+ ensure
101
+ # unpackが作った秘密鍵のコピーを消す。呼び出し側が渡したsecret_keyはそのまま残る。
102
+ SecretBuffer.wipe(classical_secret_key, pq_secret_key)
103
+ end
104
+
105
+ def free
106
+ return if @freed
107
+
108
+ @pq.free
109
+ @freed = true
110
+ end
111
+
112
+ def self.open(pq_alg_name, classical_curve = "X25519")
113
+ hybrid = new(pq_alg_name, classical_curve)
114
+ yield hybrid
115
+ ensure
116
+ hybrid&.free
117
+ end
118
+
119
+ private
120
+
121
+ # 古典側とPQ側の共有鍵を連結し、両者のciphertextとアルゴリズム名をinfoに
122
+ # バインドした上でHKDF-SHA256にかけ、最終的な共有鍵を導出する。
123
+ def combine(classical_secret, pq_secret, classical_ciphertext, pq_ciphertext)
124
+ ikm = classical_secret + pq_secret
125
+ info = [
126
+ COMBINER_LABEL,
127
+ @classical.curve,
128
+ @pq.alg_name.to_s,
129
+ classical_ciphertext,
130
+ pq_ciphertext
131
+ ].join("\x00")
132
+
133
+ # saltは空文字列(HKDFの無指定時デフォルトと等価)。TLSの鍵導出チェーンのように
134
+ # ネゴシエーション経由でsaltを共有する手段が無いスタンドアロン用途では、
135
+ # NIST SP 800-56C §8.2が「全参加者間でsaltを共有する手段が無い場合は
136
+ # 既定値(全ゼロ等)を使ってよい」と明記しており許容される。
137
+ OpenSSL::KDF.hkdf(ikm, salt: "", info: info, length: SHARED_SECRET_LENGTH, hash: "SHA256")
138
+ end
139
+
140
+ def ensure_not_freed!
141
+ raise PqcRails::Error, "this PqcRails::HybridKem instance has already been freed" if @freed
142
+ end
143
+ end
144
+ end