Module: PQCrypto::Seal

Defined in:
lib/pq_crypto/seal.rb,
lib/pq_crypto/seal/io.rb,
lib/pq_crypto/seal/core.rb,
lib/pq_crypto/seal/binary.rb,
lib/pq_crypto/seal/errors.rb,
lib/pq_crypto/seal/format.rb,
lib/pq_crypto/seal/native.rb,
lib/pq_crypto/seal/padding.rb,
lib/pq_crypto/seal/version.rb,
ext/pq_crypto_seal/pq_crypto_seal.c

Defined Under Namespace

Modules: Binary, Format, IOAPI, Padding Classes: AmbiguousRecipientStanzas, AuthenticationError, Credentials, Error, FormatError, Inspection, InvalidConfigurationError, Opened, RecipientCapacityExceeded, RecipientNotFoundError, ResourceLimitError, UnsupportedSuiteError

Constant Summary collapse

IO_DELEGATES =
%i[
  encrypt_io decrypt_io encrypt_frame_io decrypt_frame_io
  encrypt_file decrypt_file rebuild_recipients_file
  add_recipient_file drop_recipient_stanza_file rotate_dek_file
  inspect_file
].freeze
WRAP_KEM_ALGORITHM =
:ml_kem_768_x25519_xwing
HINT_DOMAIN =
"PQC-SEAL-V1-RECIPIENT-HINT\0".b
WRAP_KEY_DOMAIN =
"PQC-SEAL-V1-WRAP-KEY\0".b
WRAP_AD_DOMAIN =
"PQC-SEAL-V1-WRAP-AD\0".b
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.add_recipient(envelope, with:, recipient:, current_recipients:) ⇒ Object



128
129
130
# File 'lib/pq_crypto/seal/core.rb', line 128

def add_recipient(envelope, with:, recipient:, current_recipients:)
  rebuild_recipients(envelope, with: with, recipients: Array(current_recipients) + [recipient])
end

.assert_size!(label, actual, expected, error = InvalidConfigurationError) ⇒ Object

Raises:

  • (error)


312
313
314
315
# File 'lib/pq_crypto/seal/core.rb', line 312

def assert_size!(label, actual, expected, error = InvalidConfigurationError)
  return if actual == expected
  raise error, "#{label} must be #{expected} bytes, got #{actual}"
end

.assert_xwing_encapsulation!(encapsulated) ⇒ Object



321
322
323
324
# File 'lib/pq_crypto/seal/core.rb', line 321

def assert_xwing_encapsulation!(encapsulated)
  assert_size!("X-Wing ciphertext", encapsulated.ciphertext.bytesize, Format::XWING_CIPHERTEXT_BYTES)
  assert_size!("X-Wing shared secret", encapsulated.shared_secret.bytesize, Format::XWING_SHARED_SECRET_BYTES)
end

.assert_xwing_public_key!(public_key) ⇒ Object



317
318
319
# File 'lib/pq_crypto/seal/core.rb', line 317

def assert_xwing_public_key!(public_key)
  assert_size!("X-Wing public key", public_key.to_bytes.bytesize, Format::XWING_PUBLIC_KEY_BYTES)
end

.build_recipient_section(recipients:, capacity:, slot_size:, payload_id:, header_hash:, dek:, wrap_suite_id:) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/pq_crypto/seal/core.rb', line 226

def build_recipient_section(recipients:, capacity:, slot_size:, payload_id:, header_hash:, dek:, wrap_suite_id:)
  section_id = Native.random_bytes(Format::SECTION_ID_BYTES)
  slots = recipients.each_with_index.map do |public_key, index|
    build_slot(public_key, index, slot_size, payload_id, section_id, header_hash, dek, wrap_suite_id)
  end
  (slots.length...capacity).each do |index|
    dummy_pair = nil
    dummy_dek = nil
    begin
      dummy_pair = PQCrypto::HybridKEM.generate(WRAP_KEM_ALGORITHM)
      dummy_dek = Native.random_bytes(Format::DEK_BYTES)
      slots << build_slot(dummy_pair.public_key, index, slot_size, payload_id, section_id, header_hash, dummy_dek, wrap_suite_id)
    ensure
      dummy_pair.secret_key.wipe! if dummy_pair && dummy_pair.secret_key.respond_to?(:wipe!)
      wipe_string!(dummy_dek)
    end
  end
  Binary.u16(wrap_suite_id) + section_id + slots.join
end

.build_slot(public_key, index, slot_size, payload_id, section_id, header_hash, dek, wrap_suite_id) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/pq_crypto/seal/core.rb', line 246

def build_slot(public_key, index, slot_size, payload_id, section_id, header_hash, dek, wrap_suite_id)
  assert_xwing_public_key!(public_key)
  hint = recipient_hint(public_key, payload_id, section_id, wrap_suite_id)
  encapsulated = public_key.encapsulate
  assert_xwing_encapsulation!(encapsulated)
  wrap_nonce = Native.random_bytes(Format::NONCE_BYTES)
  slot_padding = Native.random_bytes(slot_size - Format::STANZA_BYTES)
  slot_ad = wrap_ad(header_hash, section_id, index, wrap_suite_id, hint, slot_padding)
  kek = derive_kek(encapsulated.shared_secret, payload_id, section_id, wrap_suite_id, index)
  wrapped, tag = Native.aegis256_encrypt(kek, wrap_nonce, slot_ad, dek)
  hint + encapsulated.ciphertext + wrap_nonce + wrapped + tag + slot_padding
ensure
  wipe_string!(kek) if defined?(kek)
  wipe_string!(encapsulated.shared_secret) if defined?(encapsulated) && encapsulated
end

.credential_pair(value) ⇒ Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/pq_crypto/seal/core.rb', line 344

def credential_pair(value)
  case value
  when PQCrypto::HybridKEM::Keypair then [value.secret_key, value.public_key]
  when Credentials then [value.secret_key, value.public_key]
  when Array
    unless value.length == 2
      raise InvalidConfigurationError,
            "with: must be a HybridKEM::Keypair, Seal.credentials(...), or [secret_key, public_key]"
    end
    value
  else
    raise InvalidConfigurationError,
          "with: must be a HybridKEM::Keypair, Seal.credentials(...), or [secret_key, public_key]"
  end
end

.credentials(secret_key:, public_key:) ⇒ Object



38
39
40
41
42
# File 'lib/pq_crypto/seal/core.rb', line 38

def credentials(secret_key:, public_key:)
  validate_secret_key!(secret_key)
  normalize_public_keys(public_key)
  Credentials.new(secret_key: secret_key, public_key: public_key).freeze
end

.decrypt(envelope, with:, **limits) ⇒ Object



74
75
76
# File 'lib/pq_crypto/seal/core.rb', line 74

def decrypt(envelope, with:, **limits)
  open(envelope, with: with, **limits).data
end

.derive_kek(shared_secret, payload_id, section_id, wrap_suite_id, index) ⇒ Object



307
308
309
310
# File 'lib/pq_crypto/seal/core.rb', line 307

def derive_kek(shared_secret, payload_id, section_id, wrap_suite_id, index)
  info = WRAP_KEY_DOMAIN + payload_id + section_id + Binary.u16(wrap_suite_id) + Binary.u16(index)
  Native.hkdf_sha256(shared_secret, info, Format::DEK_BYTES)
end

.digest(envelope) ⇒ Object



106
107
108
# File 'lib/pq_crypto/seal/core.rb', line 106

def digest(envelope)
  Native.sha256(String(envelope).b)
end

.drop_recipient_stanza(envelope, with:, remaining_recipients:) ⇒ Object



132
133
134
# File 'lib/pq_crypto/seal/core.rb', line 132

def drop_recipient_stanza(envelope, with:, remaining_recipients:)
  rebuild_recipients(envelope, with: with, recipients: remaining_recipients)
end

.encrypt(data, to:, metadata: "".b, public_metadata: "".b, recipient_capacity: Format::DEFAULT_RECIPIENT_CAPACITY, slot_size: Format::DEFAULT_SLOT_SIZE, padding: :padme) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/pq_crypto/seal/core.rb', line 44

def encrypt(data, to:, metadata: "".b, public_metadata: "".b,
            recipient_capacity: Format::DEFAULT_RECIPIENT_CAPACITY,
            slot_size: Format::DEFAULT_SLOT_SIZE, padding: :padme)
  data = String(data).b
   = String().b
  validate_private_metadata!()
  recipients = normalize_public_keys(to)
  capacity = Format.validate_capacity!(recipient_capacity, recipients.length)
  slot_size = Format.validate_slot_size!(slot_size)

  parts = nil
  pad_bytes = nil
  inner = nil
  parts = materialize_crypto_parts(
    recipients: recipients, capacity: capacity, slot_size: slot_size,
    padding: padding, public_metadata: ,
    content_size: data.bytesize, metadata_size: .bytesize
  )
  pad_bytes = Native.random_bytes(parts[:padded_inner_length] - parts[:raw_inner_length])
  inner = parts[:inner_prefix] +  + data + pad_bytes
  ciphertext, tag = Native.aegis256_encrypt(parts[:dek], parts[:payload_nonce], parts[:header_hash], inner)
  parts[:header] + parts[:section] + ciphertext + tag
ensure
  wipe_string!(parts[:dek]) if parts
  wipe_string!(inner)
  wipe_string!(pad_bytes)
  wipe_string!() if .is_a?(String) && !.frozen?
  wipe_string!(data) if data.is_a?(String) && !data.frozen?
end

.enforce_plaintext_limit!(content, metadata, max_plaintext_bytes) ⇒ Object

Raises:



197
198
199
200
201
202
203
# File 'lib/pq_crypto/seal/core.rb', line 197

def enforce_plaintext_limit!(content, , max_plaintext_bytes)
  return if content.bytesize <= Integer(max_plaintext_bytes)
  wipe_string!(content)
  wipe_string!()
  raise ResourceLimitError,
        "plaintext #{content.bytesize} exceeds max_plaintext_bytes #{max_plaintext_bytes}"
end

.inspect_envelope(envelope) ⇒ Object



100
101
102
103
104
# File 'lib/pq_crypto/seal/core.rb', line 100

def inspect_envelope(envelope)
  bytes = String(envelope).b
  header, section, = parse_envelope(bytes)
  Inspection.from_header(header, section, envelope_bytes: bytes.bytesize)
end

.materialize_crypto_parts(recipients:, capacity:, slot_size:, padding:, public_metadata:, content_size:, metadata_size:) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/pq_crypto/seal/core.rb', line 157

def materialize_crypto_parts(recipients:, capacity:, slot_size:, padding:, public_metadata:,
                             content_size:, metadata_size:)
  padding_policy_id = Format.padding_policy_id_for(padding)
  payload_id = Native.random_bytes(Format::PAYLOAD_ID_BYTES)
  payload_nonce = Native.random_bytes(Format::NONCE_BYTES)
  dek = Native.random_bytes(Format::DEK_BYTES)
  inner_prefix = Format.inner_prefix(content_size, )
  raw_inner_length = inner_prefix.bytesize +  + content_size

  placeholder = Format.build_header(
    payload_id: payload_id, payload_nonce: payload_nonce,
    recipient_capacity: capacity, slot_size: slot_size,
    padded_inner_length: raw_inner_length, public_metadata: ,
    padding_policy_id: padding_policy_id
  )
  fixed = placeholder.bytesize + Format.section_length_for(capacity, slot_size) + Format::TAG_BYTES
  target = Padding.target(fixed + raw_inner_length, padding)
  padded_inner_length = target - fixed
  raise InvalidConfigurationError, "invalid padding target" if padded_inner_length < raw_inner_length

  header = Format.build_header(
    payload_id: payload_id, payload_nonce: payload_nonce,
    recipient_capacity: capacity, slot_size: slot_size,
    padded_inner_length: padded_inner_length, public_metadata: ,
    padding_policy_id: padding_policy_id
  )
  header_hash = Native.sha256(header)
  section = build_recipient_section(
    recipients: recipients, capacity: capacity, slot_size: slot_size,
    payload_id: payload_id, header_hash: header_hash, dek: dek,
    wrap_suite_id: Format::WRAP_SUITE_MLKEM768_X25519_AEGIS256
  )
  {
    header: header, section: section, dek: dek, payload_id: payload_id,
    payload_nonce: payload_nonce, header_hash: header_hash,
    inner_prefix: inner_prefix, raw_inner_length: raw_inner_length,
    padded_inner_length: padded_inner_length
  }
end

.normalize_credentials(value) ⇒ Object



337
338
339
340
341
342
# File 'lib/pq_crypto/seal/core.rb', line 337

def normalize_credentials(value)
  secret_key, public_key = credential_pair(value)
  validate_secret_key!(secret_key)
  validate_public_key!(public_key, "credential public key is invalid")
  [secret_key, public_key]
end

.normalize_public_keys(value) ⇒ Object



326
327
328
329
330
331
332
333
334
335
# File 'lib/pq_crypto/seal/core.rb', line 326

def normalize_public_keys(value)
  keys = value.is_a?(Array) ? value : [value]
  raise InvalidConfigurationError, "at least one recipient is required" if keys.empty?
  keys.each { |key| validate_public_key!(key, "recipient must be an X-Wing public key (#{WRAP_KEM_ALGORITHM})") }
  fingerprints = keys.map { |key| Native.sha256(key.to_bytes) }
  if fingerprints.uniq.length != fingerprints.length
    raise InvalidConfigurationError, "recipient list contains duplicate public keys"
  end
  keys
end

.open(envelope, with:, **limits) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/pq_crypto/seal/core.rb', line 78

def open(envelope, with:, **limits)
  limits = Format::LIMIT_DEFAULTS.merge(limits)
  bytes = String(envelope).b
  Format.check_resource_limits!(
    padded_inner_length: 0, envelope_bytes: bytes.bytesize, **Format.pre_auth_limits(limits)
  )
  header, section, ciphertext, tag = parse_envelope(bytes)
  Format.check_resource_limits!(
    padded_inner_length: header.padded_inner_length,
    envelope_bytes: bytes.bytesize, **Format.pre_auth_limits(limits)
  )
  dek = unwrap_dek(header, section, with)
  header_hash = Native.sha256(header.raw)
  inner = Native.aegis256_decrypt(dek, header.payload_nonce, header_hash, ciphertext, tag)
  content, , = Format.parse_verified_inner(inner)
  enforce_plaintext_limit!(content, , limits[:max_plaintext_bytes])
  Opened.from_header(header, section, data: content, metadata: )
ensure
  wipe_string!(dek) if defined?(dek)
  wipe_string!(inner) if defined?(inner)
end

.parse_envelope(bytes) ⇒ Object

Raises:



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/pq_crypto/seal/core.rb', line 214

def parse_envelope(bytes)
  header = Format.parse_header(bytes)
  section_offset = header.raw.bytesize
  section = Format.parse_section(bytes, section_offset, header)
  payload_offset = section_offset + section.raw.bytesize
  expected = payload_offset + header.padded_inner_length + Format::TAG_BYTES
  raise FormatError, "envelope length does not match header" unless bytes.bytesize == expected
  ciphertext = bytes.byteslice(payload_offset, header.padded_inner_length).b
  tag = bytes.byteslice(payload_offset + header.padded_inner_length, Format::TAG_BYTES).b
  [header, section, ciphertext, tag]
end

.rebuild_recipients(envelope, with:, recipients:) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/pq_crypto/seal/core.rb', line 110

def rebuild_recipients(envelope, with:, recipients:)
  bytes = String(envelope).b
  header, section, ciphertext, tag = parse_envelope(bytes)
  dek = unwrap_dek(header, section, with)
  verify_payload!(header, ciphertext, tag, dek)
  public_keys = normalize_public_keys(recipients)
  Format.validate_capacity!(header.recipient_capacity, public_keys.length)
  new_section = build_recipient_section(
    recipients: public_keys, capacity: header.recipient_capacity,
    slot_size: header.slot_size, payload_id: header.payload_id,
    header_hash: Native.sha256(header.raw), dek: dek,
    wrap_suite_id: Format::WRAP_SUITE_MLKEM768_X25519_AEGIS256
  )
  header.raw + new_section + ciphertext + tag
ensure
  wipe_string!(dek) if defined?(dek)
end

.recipient_hint(public_key, payload_id, section_id, wrap_suite_id) ⇒ Object



296
297
298
# File 'lib/pq_crypto/seal/core.rb', line 296

def recipient_hint(public_key, payload_id, section_id, wrap_suite_id)
  Native.sha256(HINT_DOMAIN + payload_id + section_id + Binary.u16(wrap_suite_id) + public_key.to_bytes)
end

.rotate_dek(envelope, with:, recipients:, padding: :preserve) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/pq_crypto/seal/core.rb', line 136

def rotate_dek(envelope, with:, recipients:, padding: :preserve)
  bytes = String(envelope).b
  header, section, ciphertext, tag = parse_envelope(bytes)
  dek = unwrap_dek(header, section, with)
  header_hash = Native.sha256(header.raw)
  inner = Native.aegis256_decrypt(dek, header.payload_nonce, header_hash, ciphertext, tag)
  content, , = Format.parse_verified_inner(inner)
  padding = { to: bytes.bytesize } if padding == :preserve
  encrypt(
    content, to: recipients, metadata: ,
    public_metadata: header.,
    recipient_capacity: header.recipient_capacity,
    slot_size: header.slot_size, padding: padding
  )
ensure
  wipe_string!(dek) if defined?(dek)
  wipe_string!(inner) if defined?(inner)
  wipe_string!(content) if defined?(content)
  wipe_string!() if defined?()
end

.secure_equal?(a, b) ⇒ Boolean

Returns:

  • (Boolean)


379
380
381
382
# File 'lib/pq_crypto/seal/core.rb', line 379

def secure_equal?(a, b)
  return false unless a && b && a.bytesize == b.bytesize
  Native.secure_equal(a, b)
end

.unwrap_dek(header, section, secret_key) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/pq_crypto/seal/core.rb', line 262

def unwrap_dek(header, section, secret_key)
  secret_key, public_key = normalize_credentials(secret_key)
  assert_xwing_public_key!(public_key)
  expected_hint = recipient_hint(public_key, header.payload_id, section.section_id, section.wrap_suite_id)
  header_hash = Native.sha256(header.raw)
  successes = []

  header.recipient_capacity.times do |index|
    slot = section.raw.byteslice(section.slots_offset + index * header.slot_size, header.slot_size)
    hint = slot.byteslice(0, Format::HINT_BYTES)
    next unless secure_equal?(hint, expected_hint)

    begin
      fields = Format.split_slot(slot, header.slot_size)
      slot_ad = wrap_ad(header_hash, section.section_id, index, section.wrap_suite_id, hint, fields[:padding])
      shared = secret_key.decapsulate(fields[:kem_ciphertext])
      assert_size!("X-Wing shared secret", shared.bytesize, Format::XWING_SHARED_SECRET_BYTES, FormatError)
      kek = derive_kek(shared, header.payload_id, section.section_id, section.wrap_suite_id, index)
      successes << Native.aegis256_decrypt(kek, fields[:wrap_nonce], slot_ad, fields[:wrapped_dek], fields[:wrap_tag])
    rescue PQCrypto::Error, AuthenticationError, ArgumentError, FormatError
    ensure
      wipe_string!(shared) if defined?(shared)
      wipe_string!(kek) if defined?(kek)
    end
  end

  raise RecipientNotFoundError, "no matching recipient stanza" if successes.empty?
  if successes.length != 1
    successes.each { |candidate| wipe_string!(candidate) }
    raise AmbiguousRecipientStanzas, "multiple recipient stanzas opened"
  end
  successes.first
end

.validate_private_metadata!(metadata) ⇒ Object



373
374
375
376
377
# File 'lib/pq_crypto/seal/core.rb', line 373

def validate_private_metadata!()
  if .bytesize > Format::MAX_PRIVATE_METADATA_BYTES
    raise InvalidConfigurationError, "private metadata is too large"
  end
end

.validate_public_key!(key, message) ⇒ Object



360
361
362
363
364
365
# File 'lib/pq_crypto/seal/core.rb', line 360

def validate_public_key!(key, message)
  unless key.is_a?(PQCrypto::HybridKEM::PublicKey) && key.algorithm == WRAP_KEM_ALGORITHM
    raise InvalidConfigurationError, message
  end
  assert_xwing_public_key!(key)
end

.validate_secret_key!(key) ⇒ Object



367
368
369
370
371
# File 'lib/pq_crypto/seal/core.rb', line 367

def validate_secret_key!(key)
  unless key.is_a?(PQCrypto::HybridKEM::SecretKey) && key.algorithm == WRAP_KEM_ALGORITHM
    raise InvalidConfigurationError, "credential secret key is invalid"
  end
end

.verify_payload!(header, ciphertext, tag, dek) ⇒ Object



205
206
207
208
209
210
211
212
# File 'lib/pq_crypto/seal/core.rb', line 205

def verify_payload!(header, ciphertext, tag, dek)
  verified = Native.aegis256_decrypt(
    dek, header.payload_nonce, Native.sha256(header.raw), ciphertext, tag
  )
  true
ensure
  wipe_string!(verified) if defined?(verified)
end

.wipe_string!(value) ⇒ Object



384
385
386
387
388
389
# File 'lib/pq_crypto/seal/core.rb', line 384

def wipe_string!(value)
  return unless value.is_a?(String) && !value.frozen?
  value.replace("\0".b * value.bytesize)
rescue StandardError
  nil
end

.wrap_ad(header_hash, section_id, index, wrap_suite_id, hint, slot_padding) ⇒ Object



300
301
302
303
304
305
# File 'lib/pq_crypto/seal/core.rb', line 300

def wrap_ad(header_hash, section_id, index, wrap_suite_id, hint, slot_padding)
  Native.sha256(
    WRAP_AD_DOMAIN + header_hash + section_id + Binary.u16(index) +
      Binary.u16(wrap_suite_id) + hint + slot_padding
  )
end