tightbeam-rs 0.6.2

A secure, high-performance messaging protocol library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! ECIES (Elliptic Curve Integrated Encryption Scheme) implementation
//!
//! This module provides a generic, trait-based ECIES implementation that can
//! work with multiple elliptic curves (secp256k1, curve25519, P-256, etc.).
//!
//! # Architecture
//!
//! The implementation is split into:
//! - Generic traits for ECIES key operations
//! - Concrete implementations for specific curves (currently secp256k1)
//! - Curve-agnostic encryption/decryption functions
//!
//! # ECIES Protocol
//!
//! **Encryption:**
//! 1. Generate ephemeral keypair (r, R = r·G)
//! 2. Compute shared secret: S = r·P (where P is recipient's public key)
//! 3. Derive key: k_enc = KDF(C0, S) where C0 is ephemeral pubkey
//! 4. Encrypt: c = AEAD.Encrypt(k_enc, plaintext) with a random nonce
//! 5. Output: [R || nonce || ciphertext || tag]
//!
//! **Decryption:**
//! 1. Parse [R || nonce || ciphertext || tag] from ciphertext
//! 2. Compute shared secret: S = d·R (where d is recipient's private key)
//! 3. Derive key: k_enc = KDF(C0, S)
//! 4. Decrypt: plaintext = AEAD.Decrypt(k_enc, nonce, ciphertext, tag)
//!
//! # Security
//!
//! This implementation uses constant-time cryptographic primitives
//! - ECDH operations (k256): constant-time scalar multiplication
//! - AES-256-GCM: constant-time encryption and tag verification  
//! - HKDF-SHA3-256: constant-time key derivation

use rand_core::{CryptoRng, CryptoRngCore, OsRng, RngCore};

use crate::asn1::ObjectIdentifier;
use crate::constants::{AES_GCM_NONCE_SIZE, AES_GCM_TAG_SIZE, EC_PUBKEY_COMPRESSED_SIZE, TIGHTBEAM_ECIES_KDF_INFO};
use crate::der::oid::AssociatedOid;

use crate::crypto::aead::{Aead, Aes256Gcm, KeyInit, Payload};
use crate::crypto::kdf::{ecies_kdf, HkdfSha3_256, KdfError};
use crate::crypto::secret::{Secret, SecretSlice};
use crate::crypto::sign::ecdsa::k256::ecdh::EphemeralSecret;
use crate::crypto::sign::ecdsa::k256::elliptic_curve::sec1::ToEncodedPoint;
use crate::crypto::sign::ecdsa::k256::{PublicKey, SecretKey};

// ============================================================================
// RNG Wrapper for Trait Object Compatibility
// ============================================================================

/// Wrapper to adapt `dyn CryptoRngCore` to the `CryptoRng + RngCore` bounds
/// required by `EphemeralSecret::random`.
///
/// `EphemeralSecret::random` requires a `Sized` RNG parameter, but we want to
/// accept trait objects for flexibility. This wrapper forwards all RNG methods
/// to the underlying trait object.
struct RngWrapper<'a>(&'a mut dyn CryptoRngCore);

impl RngCore for RngWrapper<'_> {
	fn next_u32(&mut self) -> u32 {
		self.0.next_u32()
	}

	fn next_u64(&mut self) -> u64 {
		self.0.next_u64()
	}

	fn fill_bytes(&mut self, dest: &mut [u8]) {
		self.0.fill_bytes(dest)
	}

	fn try_fill_bytes(&mut self, dest: &mut [u8]) -> core::result::Result<(), rand_core::Error> {
		self.0.try_fill_bytes(dest)
	}
}

impl CryptoRng for RngWrapper<'_> {}

// ============================================================================
// Generic ECIES Traits
// ============================================================================
/// Trait for ECIES public keys with key exchange capability
pub trait EciesPublicKeyOps: Clone + PartialEq + Eq {
	/// Associated secret key type for this public key
	type SecretKey: EciesSecretKeyOps<PublicKey = Self>;

	/// The byte representation size for this public key
	const PUBLIC_KEY_SIZE: usize;

	/// Deserialize a public key from bytes
	fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self>
	where
		Self: Sized;

	/// Serialize the public key to bytes
	fn to_bytes(&self) -> Vec<u8>;
}

/// Trait for ECIES secret keys with key exchange and generation capability
pub trait EciesSecretKeyOps: Clone {
	/// Associated public key type
	type PublicKey: EciesPublicKeyOps;

	/// The byte representation size for this secret key
	const SECRET_KEY_SIZE: usize;

	/// Generate a new random secret key
	fn random<R: CryptoRng + RngCore>(rng: &mut R) -> Self;

	/// Get the corresponding public key
	fn public_key(&self) -> Self::PublicKey;

	/// Perform ECDH key agreement with a public key, returning raw shared secret bytes
	fn diffie_hellman(&self, public_key: &Self::PublicKey) -> SecretSlice<u8>;
}

/// Trait for ephemeral key generation in ECIES encryption
pub trait EciesEphemeral {
	/// Associated public key type
	type PublicKey: EciesPublicKeyOps;

	/// Generate a new ephemeral keypair and return (public_key_bytes, shared_secret_bytes)
	fn generate_ephemeral(
		recipient_pubkey: &Self::PublicKey,
		rng: &mut dyn rand_core::CryptoRngCore,
	) -> Result<(Vec<u8>, SecretSlice<u8>)>;
}

// ============================================================================
// secp256k1 Implementation
// ============================================================================

#[cfg(feature = "derive")]
use crate::Errorizable;

/// Errors specific to ECIES operations
#[cfg_attr(feature = "derive", derive(Errorizable))]
#[derive(Debug, Clone)]
pub enum EciesError {
	/// Invalid ciphertext format
	#[cfg_attr(feature = "derive", error("Invalid ECIES ciphertext format"))]
	InvalidCiphertext,

	/// Invalid public key
	#[cfg_attr(feature = "derive", error("Invalid ECIES public key: {0}"))]
	InvalidPublicKey(crate::crypto::sign::ecdsa::k256::elliptic_curve::Error),

	/// Invalid secret key
	#[cfg_attr(feature = "derive", error("Invalid ECIES secret key: {0}"))]
	InvalidSecretKey(crate::crypto::sign::ecdsa::k256::elliptic_curve::Error),

	/// Encryption failed
	#[cfg_attr(feature = "derive", error("ECIES encryption failed: {0}"))]
	EncryptionFailed(crate::crypto::aead::Error),

	/// Decryption failed
	#[cfg_attr(feature = "derive", error("ECIES decryption failed: {0}"))]
	DecryptionFailed(crate::crypto::aead::Error),

	/// Key derivation failed
	#[cfg_attr(feature = "derive", error("ECIES key derivation failed: {0}"))]
	#[cfg_attr(feature = "derive", from)]
	Kdf(#[cfg_attr(feature = "derive", from)] KdfError),
}

crate::impl_error_display!(EciesError {
	InvalidCiphertext => "Invalid ECIES ciphertext format",
	InvalidPublicKey(e) => "Invalid ECIES public key: {e}",
	InvalidSecretKey(e) => "Invalid ECIES secret key: {e}",
	EncryptionFailed(e) => "ECIES encryption failed: {e}",
	DecryptionFailed(e) => "ECIES decryption failed: {e}",
	Kdf(e) => "ECIES key derivation failed: {e}",
});

/// A specialized Result type for ECIES operations
pub type Result<T> = core::result::Result<T, EciesError>;

// ============================================================================
// Trait implementations for k256 types (secp256k1)
// ============================================================================

impl EciesPublicKeyOps for PublicKey {
	type SecretKey = SecretKey;

	const PUBLIC_KEY_SIZE: usize = EC_PUBKEY_COMPRESSED_SIZE;

	fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
		PublicKey::from_sec1_bytes(bytes.as_ref()).map_err(EciesError::InvalidPublicKey)
	}

	fn to_bytes(&self) -> Vec<u8> {
		let point = self.to_encoded_point(true);
		point.as_bytes().to_vec()
	}
}

impl EciesSecretKeyOps for SecretKey {
	type PublicKey = PublicKey;

	const SECRET_KEY_SIZE: usize = 32;

	fn random<R: CryptoRng + RngCore>(rng: &mut R) -> Self {
		SecretKey::random(rng)
	}

	fn public_key(&self) -> Self::PublicKey {
		SecretKey::public_key(self)
	}

	fn diffie_hellman(&self, public_key: &Self::PublicKey) -> SecretSlice<u8> {
		let shared_secret = k256::ecdh::diffie_hellman(self.to_nonzero_scalar(), public_key.as_affine());
		let v = shared_secret.raw_secret_bytes().to_vec().into_boxed_slice();
		Secret::from(v)
	}
}

impl core::convert::TryFrom<SecretSlice<u8>> for SecretKey {
	type Error = EciesError;
	fn try_from(bytes: SecretSlice<u8>) -> Result<Self> {
		use crate::crypto::secret::ToInsecure;
		let raw = bytes.to_insecure().map_err(EciesError::from)?;
		SecretKey::from_slice(&raw).map_err(EciesError::InvalidSecretKey)
	}
}

impl From<&SecretKey> for SecretSlice<u8> {
	fn from(sk: &SecretKey) -> Self {
		let v = SecretKey::to_bytes(sk).to_vec();
		Secret::from(v.into_boxed_slice())
	}
}

impl EciesEphemeral for SecretKey {
	type PublicKey = PublicKey;

	fn generate_ephemeral(
		recipient_pubkey: &Self::PublicKey,
		rng: &mut dyn CryptoRngCore,
	) -> Result<(Vec<u8>, SecretSlice<u8>)> {
		let mut wrapper = RngWrapper(rng);
		let ephemeral_secret = EphemeralSecret::random(&mut wrapper);
		let ephemeral_pubkey = ephemeral_secret.public_key();

		// Perform ECDH to get shared secret
		let shared_secret = ephemeral_secret.diffie_hellman(recipient_pubkey);

		let ephemeral_point = ephemeral_pubkey.to_encoded_point(true);
		let ephemeral_bytes = ephemeral_point.as_bytes().to_vec();
		let shared_bytes = Secret::from(shared_secret.raw_secret_bytes().to_vec().into_boxed_slice());
		Ok((ephemeral_bytes, shared_bytes))
	}
}

/// Trait for ECIES encrypted messages with curve-specific sizes
pub trait EciesMessageOps: Sized {
	/// Size of the ephemeral public key in bytes (curve-specific)
	const PUBKEY_SIZE: usize;

	/// Parse from wire format: [ephemeral_pubkey || ciphertext_with_tag]
	fn from_bytes(bytes: &[u8]) -> Result<Self>;

	/// Serialize to wire format: [ephemeral_pubkey || ciphertext_with_tag]
	fn to_bytes(&self) -> Vec<u8>;

	/// Get ephemeral public key bytes
	fn ephemeral_pubkey(&self) -> &[u8];

	/// Get ciphertext bytes (nonce || encrypted_data || tag)
	fn ciphertext(&self) -> &[u8];
}

/// ECIES encrypted message for secp256k1 curve
///
/// The wire format consists of:
/// - `ephemeral_pubkey`: 33 bytes (compressed secp256k1 public key)
/// - `nonce`: 12 bytes (AES-GCM nonce)
/// - `ciphertext`: variable length (encrypted plaintext)
/// - `tag`: 16 bytes (AES-GCM authentication tag, appended to ciphertext)
pub struct Secp256k1EciesMessage {
	/// Ephemeral public key (serialized, compressed SEC1 format)
	ephemeral_pubkey: Vec<u8>,
	/// Nonce + encrypted data + authentication tag
	ciphertext: Vec<u8>,
}

impl Secp256k1EciesMessage {
	/// Minimum ciphertext size (nonce + tag)
	const MIN_CIPHERTEXT_SIZE: usize = AES_GCM_NONCE_SIZE + AES_GCM_TAG_SIZE;

	/// Parse from wire format: [ephemeral_pubkey || ciphertext_with_tag]
	pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
		let bytes = bytes.as_ref();
		if bytes.len() < EC_PUBKEY_COMPRESSED_SIZE + Self::MIN_CIPHERTEXT_SIZE {
			return Err(EciesError::InvalidCiphertext);
		}

		let ephemeral_pubkey = bytes[0..EC_PUBKEY_COMPRESSED_SIZE].to_vec();
		let ciphertext = bytes[EC_PUBKEY_COMPRESSED_SIZE..].to_vec();
		if ciphertext.len() < Self::MIN_CIPHERTEXT_SIZE {
			return Err(EciesError::InvalidCiphertext);
		}

		Ok(Self { ephemeral_pubkey, ciphertext })
	}

	/// Serialize to wire format: [ephemeral_pubkey || ciphertext_with_tag]
	pub fn to_bytes(&self) -> Vec<u8> {
		let mut bytes = Vec::with_capacity(self.ephemeral_pubkey.len() + self.ciphertext.len());
		bytes.extend_from_slice(&self.ephemeral_pubkey);
		bytes.extend_from_slice(&self.ciphertext);
		bytes
	}

	/// Mutable access to ephemeral public key bytes (for tampering tests)
	#[cfg(test)]
	pub(crate) fn ephemeral_pubkey_mut(&mut self) -> &mut Vec<u8> {
		&mut self.ephemeral_pubkey
	}

	/// Mutable access to ciphertext bytes (for tampering tests)
	#[cfg(test)]
	pub(crate) fn ciphertext_mut(&mut self) -> &mut Vec<u8> {
		&mut self.ciphertext
	}
}

impl EciesMessageOps for Secp256k1EciesMessage {
	const PUBKEY_SIZE: usize = EC_PUBKEY_COMPRESSED_SIZE;

	fn from_bytes(bytes: &[u8]) -> Result<Self> {
		Self::from_bytes(bytes)
	}

	fn to_bytes(&self) -> Vec<u8> {
		Self::to_bytes(self)
	}

	fn ephemeral_pubkey(&self) -> &[u8] {
		&self.ephemeral_pubkey
	}

	fn ciphertext(&self) -> &[u8] {
		&self.ciphertext
	}
}

/// Encrypt plaintext using ECIES with recipient's public key
///
/// # Arguments
/// * `recipient_pubkey` - Recipient's public key (implements EciesPublicKeyOps)
/// * `plaintext` - Data to encrypt
/// * `associated_data` - Optional authenticated associated data (AAD)
/// * `rng` - Optional cryptographically secure random number generator (uses OsRng if not provided)
///
/// # Returns
/// Encrypted message containing ephemeral public key and ciphertext
///
/// # Type Parameters
/// * `PK` - Public key type implementing EciesPublicKeyOps
/// * `P` - Plaintext type that can be converted to bytes
/// * `R` - Random number generator type (optional, defaults to OsRng)
/// * `M` - Message type implementing EciesMessageOps
pub fn encrypt<PK, P, R, M>(
	recipient_pubkey: &PK,
	plaintext: P,
	associated_data: Option<&[u8]>,
	rng: Option<&mut R>,
) -> Result<M>
where
	PK: EciesPublicKeyOps,
	PK::SecretKey: EciesEphemeral<PublicKey = PK>,
	P: AsRef<[u8]>,
	R: CryptoRng + RngCore,
	M: EciesMessageOps,
{
	let plaintext = plaintext.as_ref();

	// Helper macro to avoid code duplication
	macro_rules! do_encrypt {
		($rng:expr) => {{
			// Use the trait method to generate ephemeral key and shared secret
			let (ephemeral_bytes, shared_secret) = PK::SecretKey::generate_ephemeral(recipient_pubkey, $rng)?;

			// Derive encryption key using KDF (includes C0 for non-malleability)
			let k_enc = ecies_kdf::<HkdfSha3_256>(&ephemeral_bytes, shared_secret, TIGHTBEAM_ECIES_KDF_INFO, None)?;

			// Encrypt using AES-256-GCM
			let key = crate::crypto::utils::key_from_slice(&k_enc[..32]);
			let cipher = Aes256Gcm::new(&key);

			// Generate random nonce (96 bits for GCM)
			let mut nonce_bytes = [0u8; AES_GCM_NONCE_SIZE];
			$rng.fill_bytes(&mut nonce_bytes);
			let nonce = crate::crypto::utils::nonce_from_slice::<Aes256Gcm>(&nonce_bytes);

			// Prepare payload with optional AAD
			let payload = match associated_data {
				Some(aad) => Payload { msg: plaintext, aad },
				None => Payload { msg: plaintext, aad: b"" },
			};

			// Encrypt and prepend nonce in a single allocation
			let ciphertext = cipher.encrypt(&nonce, payload).map_err(EciesError::EncryptionFailed)?;
			let encrypted_len = ciphertext.len();
			let mut final_ciphertext = Vec::with_capacity(AES_GCM_NONCE_SIZE + encrypted_len);
			final_ciphertext.extend_from_slice(&nonce_bytes);
			final_ciphertext.extend_from_slice(&ciphertext);

			// Construct message from concatenated bytes (avoid extra allocation)
			let total_len = ephemeral_bytes.len() + final_ciphertext.len();
			let mut wire_bytes = Vec::with_capacity(total_len);
			wire_bytes.extend_from_slice(&ephemeral_bytes);
			wire_bytes.extend_from_slice(&final_ciphertext);
			M::from_bytes(&wire_bytes)
		}};
	}

	// Use provided RNG or default to OsRng
	match rng {
		Some(r) => do_encrypt!(r),
		None => do_encrypt!(&mut OsRng),
	}
}

pub fn decrypt<SK, M>(recipient_seckey: &SK, message: &M, associated_data: Option<&[u8]>) -> Result<SecretSlice<u8>>
where
	SK: EciesSecretKeyOps,
	M: EciesMessageOps,
{
	// 1. Parse ephemeral public key
	let ephemeral_pubkey = <SK::PublicKey as EciesPublicKeyOps>::from_bytes(message.ephemeral_pubkey())?;
	// 2. Perform ECDH to get shared secret
	let shared_secret = recipient_seckey.diffie_hellman(&ephemeral_pubkey);
	// 3. Derive encryption key using KDF (includes C0 for non-malleability)
	// Uses SHA3-256 with protocol versioning via info parameter
	// Derives 32-byte key for AES-256-GCM authenticated encryption
	let k_enc = ecies_kdf::<HkdfSha3_256>(message.ephemeral_pubkey(), shared_secret, TIGHTBEAM_ECIES_KDF_INFO, None)?;

	// 4. Extract nonce and ciphertext
	let ciphertext_bytes = message.ciphertext();
	if ciphertext_bytes.len() < AES_GCM_NONCE_SIZE + AES_GCM_TAG_SIZE {
		return Err(EciesError::InvalidCiphertext);
	}
	let nonce = crate::crypto::utils::nonce_from_slice::<Aes256Gcm>(&ciphertext_bytes[0..AES_GCM_NONCE_SIZE]);
	let ciphertext_with_tag = &ciphertext_bytes[AES_GCM_NONCE_SIZE..];

	// 5. Decrypt using AES-256-GCM
	let key = crate::crypto::utils::key_from_slice(&k_enc[..32]);
	let cipher = Aes256Gcm::new(&key);

	// Prepare payload with optional AAD
	let payload = match associated_data {
		Some(aad) => Payload { msg: ciphertext_with_tag, aad },
		None => Payload { msg: ciphertext_with_tag, aad: b"" },
	};

	// Decrypt and verify tag
	let plaintext = cipher.decrypt(&nonce, payload).map_err(EciesError::DecryptionFailed)?;
	Ok(Secret::from(plaintext.into_boxed_slice()))
}

#[cfg(feature = "x509")]
crate::define_oid_wrapper!(
	/// OID wrapper for ECIES with secp256k1
	EciesSecp256k1Oid,
	"1.3.132.1.12.0"
);

// ============================================================================
// Encryptor/Decryptor Trait Implementations
// ============================================================================

/// ECIES encryptor - encrypts messages to a recipient's public key.
///
/// This type implements the `Encryptor` trait, allowing it to be used
/// with `FrameBuilder::with_encryptor()` for asymmetric message encryption.
///
/// # Example
/// ```ignore
/// let encryptor = EciesEncryptor::new(recipient_pubkey);
/// let frame = compose! {
///     V2: id: b"msg-001",
///         message: payload,
///         encryptor<EciesSecp256k1Oid, _>: encryptor
/// }?;
/// ```
#[cfg(feature = "x509")]
pub struct EciesEncryptor {
	recipient_pubkey: PublicKey,
}

#[cfg(feature = "x509")]
impl EciesEncryptor {
	/// Create a new ECIES encryptor for the given recipient's public key.
	pub fn new(recipient_pubkey: PublicKey) -> Self {
		Self { recipient_pubkey }
	}

	/// Create from raw public key bytes (SEC1 format).
	pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
		let pubkey = PublicKey::from_bytes(bytes)?;
		Ok(Self::new(pubkey))
	}
}

#[cfg(feature = "x509")]
impl crate::crypto::aead::Encryptor<EciesSecp256k1Oid> for EciesEncryptor {
	fn encrypt_content(
		&self,
		data: impl AsRef<[u8]>,
		_nonce: impl AsRef<[u8]>, // Ignored - ECIES generates its own nonce
		content_type: Option<ObjectIdentifier>,
	) -> crate::error::Result<crate::EncryptedContentInfo> {
		// Use existing ECIES encrypt function
		let ecies_msg: Secp256k1EciesMessage =
			encrypt(&self.recipient_pubkey, data.as_ref(), None, None::<&mut OsRng>)?;

		// Store the full ECIES message (ephemeral pubkey + ciphertext) as encrypted content
		let encrypted_bytes = ecies_msg.to_bytes();
		let content_type = content_type.unwrap_or(crate::oids::DATA);

		// No nonce parameter needed - ECIES embeds the ephemeral pubkey
		let content_enc_alg = crate::AlgorithmIdentifier { oid: EciesSecp256k1Oid::OID, parameters: None };
		let encrypted_content = Some(crate::der::asn1::OctetString::new(encrypted_bytes)?);

		Ok(crate::EncryptedContentInfo { content_type, content_enc_alg, encrypted_content })
	}
}

/// ECIES decryptor - decrypts messages with recipient's secret key.
///
/// This type implements the `Decryptor` trait for decrypting ECIES-encrypted
/// messages.
///
/// # Example
/// ```ignore
/// let decryptor = EciesDecryptor::new(my_secret_key);
/// let plaintext = frame.decrypt(&decryptor)?;
/// ```
#[cfg(feature = "x509")]
pub struct EciesDecryptor {
	secret_key: SecretKey,
}

#[cfg(feature = "x509")]
impl EciesDecryptor {
	/// Create a new ECIES decryptor with the given secret key.
	pub fn new(secret_key: SecretKey) -> Self {
		Self { secret_key }
	}
}

#[cfg(feature = "x509")]
impl crate::crypto::aead::Decryptor for EciesDecryptor {
	fn decrypt_content(&self, info: &crate::EncryptedContentInfo) -> crate::error::Result<Vec<u8>> {
		// Extract the encrypted bytes
		let encrypted_bytes = info
			.encrypted_content
			.as_ref()
			.ok_or(crate::TightBeamError::MissingEncryptionInfo)?
			.as_bytes();

		// Parse as ECIES message
		let ecies_msg = Secp256k1EciesMessage::from_bytes(encrypted_bytes)?;
		// Decrypt using ECIES
		let plaintext = decrypt(&self.secret_key, &ecies_msg, None)?;

		// Convert SecretSlice to Vec<u8>
		use crate::crypto::secret::ToInsecure;
		Ok(plaintext.to_insecure()?.to_vec())
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::crypto::secret::ToInsecure;
	use rand_core::OsRng;

	// Helper to create a key pair
	fn keypair() -> (SecretKey, PublicKey) {
		let mut rng = OsRng;
		let secret = SecretKey::random(&mut rng);
		let public = secret.public_key();
		(secret, public)
	}

	// Helper for encryption roundtrip
	fn roundtrip(plaintext: &[u8], aad: Option<&[u8]>) -> Result<()> {
		let (secret, public) = keypair();
		let encrypted = encrypt::<_, _, _, Secp256k1EciesMessage>(&public, plaintext, aad, None::<&mut OsRng>)?;
		let decrypted = decrypt(&secret, &encrypted, aad)?;
		assert_eq!(plaintext, &decrypted.to_insecure().map_err(EciesError::from)?[..]);
		Ok(())
	}

	#[test]
	fn test_ecies_encryption() -> Result<()> {
		// Test cases: (plaintext, aad)
		let cases = [
			(&b"Hello, ECIES!"[..], None),
			(b"Secret message", Some(&b"authenticated data"[..])),
			(b"", None),
			// cspell:disable-next-line
			(b"The quick brown fox jumps over the lazy dog. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", None),
			(b"\x00\x01\x02\x03\xFF\xFE\xFD\xFC", None),
			(b"Payload", Some(&b"version:1|timestamp:12345|nonce:abcdef"[..])),
		];

		for (plaintext, aad) in cases {
			roundtrip(plaintext, aad)?;
		}

		Ok(())
	}

	#[test]
	fn test_aad_validation() -> Result<()> {
		let mut rng = OsRng;
		let (secret, public) = keypair();
		let plaintext = b"Secret message";
		let correct_aad = b"authenticated data";

		// Test with explicit RNG to verify RNG parameter works
		let encrypted =
			encrypt::<_, _, _, Secp256k1EciesMessage>(&public, plaintext, Some(correct_aad), Some(&mut rng))?;
		// Test cases: (aad, should_succeed)
		let cases = [
			(Some(&correct_aad[..]), true),
			(Some(&b"wrong data"[..]), false),
			(None, false),
			(Some(&b""[..]), false),
		];

		for (aad, should_succeed) in cases {
			let result = decrypt(&secret, &encrypted, aad);
			assert_eq!(result.is_ok(), should_succeed);
			if should_succeed {
				assert_eq!(&plaintext[..], &result?.to_insecure().map_err(EciesError::from)?[..]);
			}
		}

		Ok(())
	}

	#[test]
	fn test_serialization() -> Result<()> {
		let (secret, public) = keypair();
		let plaintext = b"Test serialization";

		// Message serialization roundtrip
		let encrypted = encrypt::<_, _, _, Secp256k1EciesMessage>(&public, plaintext, None, None::<&mut OsRng>)?;
		let bytes = encrypted.to_bytes();
		let parsed = Secp256k1EciesMessage::from_bytes(&bytes)?;
		let decrypted = decrypt(&secret, &parsed, None)?;
		assert_eq!(&plaintext[..], &decrypted.to_insecure().map_err(EciesError::from)?[..]);

		// Key serialization roundtrip using traits
		let secret_bytes: SecretSlice<u8> = (&secret).into();
		let public_bytes = public.to_bytes();

		let secret2 = SecretKey::try_from(secret_bytes)?;
		let public2 = PublicKey::from_bytes(&public_bytes)?;

		assert_eq!(public.to_bytes(), public2.to_bytes());
		assert_eq!(secret.public_key().to_bytes(), secret2.public_key().to_bytes());

		Ok(())
	}

	#[test]
	fn test_security_properties() -> Result<()> {
		let plaintext = b"Sensitive data";

		// Wrong recipient cannot decrypt
		let (_, public1) = keypair();
		let (secret2, _) = keypair();

		let encrypted = encrypt::<_, _, _, Secp256k1EciesMessage>(&public1, plaintext, None, None::<&mut OsRng>)?;
		let result = decrypt(&secret2, &encrypted, None);

		if let Ok(decrypted) = result {
			assert_ne!(&plaintext[..], &decrypted.to_insecure().map_err(EciesError::from)?[..]);
		}

		// Tampered ciphertext should fail authentication
		let (secret, public) = keypair();

		let tamper_functions: [fn(&mut Secp256k1EciesMessage); 4] = [
			|msg| {
				if let Some(byte) = msg.ciphertext_mut().last_mut() {
					*byte ^= 0xFF;
				}
			},
			|msg| {
				if let Some(byte) = msg.ciphertext_mut().first_mut() {
					*byte ^= 0xFF;
				}
			},
			|msg| {
				let len = msg.ciphertext_mut().len().saturating_sub(1);
				msg.ciphertext_mut().truncate(len);
			},
			|msg| {
				if let Some(byte) = msg.ephemeral_pubkey_mut().first_mut() {
					*byte ^= 0xFF;
				}
			},
		];

		for tamper_fn in tamper_functions {
			let mut encrypted =
				encrypt::<_, _, _, Secp256k1EciesMessage>(&public, plaintext, None, None::<&mut OsRng>)?;
			tamper_fn(&mut encrypted);
			assert!(decrypt(&secret, &encrypted, None).is_err());
		}

		Ok(())
	}

	#[test]
	fn test_edge_cases() -> Result<()> {
		// Invalid ciphertext formats
		let invalid_ciphertexts = [
			vec![],
			vec![0u8; 32],
			vec![0u8; 33], // Missing ciphertext
			vec![0u8; 45], // 33 + 12 (less than min 33+16)
		];

		for data in invalid_ciphertexts {
			assert!(Secp256k1EciesMessage::from_bytes(&data).is_err());
		}

		// Invalid key formats
		assert!(PublicKey::from_bytes([0xFFu8; 33]).is_err());
		assert!(SecretKey::try_from(Secret::from(vec![0x00u8; 32].into_boxed_slice())).is_err());

		Ok(())
	}
}