multi-key 1.0.6

Multikey self-describing cryptographic key data
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
// SPDX-License-Identifier: Apache-2.0
//! X25519-sntrup761 hybrid KEM multikey view; combines X25519 ECDH with sntrup761 KEM,
//! ChaCha20-Poly1305 AEAD, and BLAKE3 KDF.

use crate::{
    error::{AttributesError, ConversionsError, SealError},
    views::{aead, Views},
    AttrId, AttrView, Builder, ConvView, DataView, Error, FingerprintView, Multikey, OpenView,
    SealView,
};
use multi_codec::Codec;
use multi_hash::{mh, Multihash};
use multi_trait::TryDecodeFrom;
use multi_util::Varbytes;
use sntrup::sntrup761::{self, EncapsulationKey};
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroizing;

/// Compatibility wrapper: allows `rand 0.8` OsRng to satisfy `rand_core 0.10`
/// `CryptoRng` required by the `sntrup` crate.
struct OsRng010;

impl rand_core::TryRng for OsRng010 {
    type Error = core::convert::Infallible;

    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
        Ok(rand_core::Rng::next_u32(&mut rand::rng()))
    }
    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
        Ok(rand_core::Rng::next_u64(&mut rand::rng()))
    }
    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
        rand_core::Rng::fill_bytes(&mut rand::rng(), dst);
        Ok(())
    }
}
impl rand_core::TryCryptoRng for OsRng010 {}

const X25519_SEED_LEN: usize = 32;
const SNTRUP761_SEED_LEN: usize = 32;
const PRIV_SEED_LEN: usize = X25519_SEED_LEN + SNTRUP761_SEED_LEN; // 64
const X25519_PUB_LEN: usize = 32;
const SNTRUP761_PUB_LEN: usize = 1158;
const PUB_KEY_LEN: usize = X25519_PUB_LEN + SNTRUP761_PUB_LEN; // 1190

/// Decoded sealed message: (ephemeral_x25519_pub, sntrup761_ct, nonce, ciphertext+tag)
type SealedParts = (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>);

/// Only ChaCha20-Poly1305 allowed per spec
fn is_aead_allowed(codec: Codec) -> bool {
    codec == Codec::Chacha20Poly1305
}

pub(crate) struct View<'a> {
    mk: &'a Multikey,
}

impl<'a> TryFrom<&'a Multikey> for View<'a> {
    type Error = Error;

    fn try_from(mk: &'a Multikey) -> Result<Self, Self::Error> {
        Ok(Self { mk })
    }
}

impl<'a> AttrView for View<'a> {
    fn is_encrypted(&self) -> bool {
        false
    }
    fn is_secret_key(&self) -> bool {
        self.mk.codec == Codec::X25519Sntrup761Priv
    }
    fn is_public_key(&self) -> bool {
        self.mk.codec == Codec::X25519Sntrup761Pub
    }
    fn is_secret_key_share(&self) -> bool {
        false
    }
}

impl<'a> DataView for View<'a> {
    fn key_bytes(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
        let key = self
            .mk
            .attributes
            .get(&AttrId::KeyData)
            .ok_or(AttributesError::MissingKey)?;
        Ok(key.clone())
    }
    fn secret_bytes(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
        if !self.is_secret_key() {
            return Err(AttributesError::NotSecretKey(self.mk.codec).into());
        }
        self.key_bytes()
    }
}

impl<'a> ConvView for View<'a> {
    fn to_public_key(&self) -> Result<Multikey, Error> {
        let secret_bytes = {
            let kd = self.mk.data_view()?;
            kd.secret_bytes()?
        };

        if secret_bytes.len() != PRIV_SEED_LEN {
            return Err(
                ConversionsError::SecretKeyFailure("invalid hybrid seed length".into()).into(),
            );
        }

        // X25519 public key
        let x25519_seed: [u8; 32] = secret_bytes[..X25519_SEED_LEN]
            .try_into()
            .map_err(|_| ConversionsError::SecretKeyFailure("invalid x25519 seed".into()))?;
        let x25519_secret = StaticSecret::from(x25519_seed);
        let x25519_pub = PublicKey::from(&x25519_secret);

        // Sntrup761 public key
        let sntrup_seed: [u8; 32] = secret_bytes[X25519_SEED_LEN..PRIV_SEED_LEN]
            .try_into()
            .map_err(|_| ConversionsError::SecretKeyFailure("invalid sntrup761 seed".into()))?;
        let (ek, _dk) = sntrup761::generate_key_deterministic(&sntrup_seed);

        // Concatenate: x25519_pub (32) || sntrup761_pub (1158)
        let mut pub_bytes = Vec::with_capacity(PUB_KEY_LEN);
        pub_bytes.extend_from_slice(x25519_pub.as_bytes());
        pub_bytes.extend_from_slice(ek.as_ref());

        Builder::new(Codec::X25519Sntrup761Pub)
            .with_comment(&self.mk.comment)
            .with_key_bytes(&pub_bytes)
            .try_build()
    }

    fn to_ssh_public_key(&self) -> Result<ssh_key::PublicKey, Error> {
        Err(ConversionsError::UnsupportedAlgorithm(
            "X25519-sntrup761 not supported in SSH key format".into(),
        )
        .into())
    }
    fn to_ssh_private_key(&self) -> Result<ssh_key::PrivateKey, Error> {
        Err(ConversionsError::UnsupportedAlgorithm(
            "X25519-sntrup761 not supported in SSH key format".into(),
        )
        .into())
    }
}

impl<'a> FingerprintView for View<'a> {
    fn fingerprint(&self, codec: Codec) -> Result<Multihash, Error> {
        let pub_bytes = if self.is_secret_key() {
            let pk = self.to_public_key()?;
            let dv = pk.data_view()?;
            dv.key_bytes()?
        } else {
            self.key_bytes()?
        };
        Ok(mh::Builder::new_from_bytes(codec, pub_bytes.as_slice())?.try_build()?)
    }
}

/// Combine shared secrets using BLAKE3:
/// ss = BLAKE3(label || ss_sntrup || ss_x25519 || sntrup_ct || ephemeral_x25519_pub)
fn combine_shared_secrets(
    ss_sntrup: &[u8],
    ss_x25519: &[u8],
    sntrup_ct: &[u8],
    ephemeral_x25519_pub: &[u8],
) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"x25519-sntrup761-hpke");
    hasher.update(ss_sntrup);
    hasher.update(ss_x25519);
    hasher.update(sntrup_ct);
    hasher.update(ephemeral_x25519_pub);
    *hasher.finalize().as_bytes()
}

/// Encode sealed message: [ephemeral_x25519_pub Varbytes][sntrup761_ct Varbytes][nonce Varbytes][ct+tag Varbytes]
fn encode_sealed(ephemeral_pub: &[u8], sntrup_ct: &[u8], nonce: &[u8], ct_tag: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    out.append(&mut Varbytes::new(ephemeral_pub.to_vec()).into());
    out.append(&mut Varbytes::new(sntrup_ct.to_vec()).into());
    out.append(&mut Varbytes::new(nonce.to_vec()).into());
    out.append(&mut Varbytes::new(ct_tag.to_vec()).into());
    out
}

/// Decode sealed message
fn decode_sealed(data: &[u8]) -> Result<SealedParts, SealError> {
    let (ephemeral_pub, ptr) = Varbytes::try_decode_from(data)
        .map_err(|_| SealError::InvalidFormat("missing ephemeral public key".into()))?;
    let (sntrup_ct, ptr) = Varbytes::try_decode_from(ptr)
        .map_err(|_| SealError::InvalidFormat("missing sntrup761 ciphertext".into()))?;
    let (nonce, ptr) = Varbytes::try_decode_from(ptr)
        .map_err(|_| SealError::InvalidFormat("missing nonce".into()))?;
    let (ct_tag, _) = Varbytes::try_decode_from(ptr)
        .map_err(|_| SealError::InvalidFormat("missing ciphertext".into()))?;
    Ok((
        ephemeral_pub.to_inner(),
        sntrup_ct.to_inner(),
        nonce.to_inner(),
        ct_tag.to_inner(),
    ))
}

impl<'a> SealView for View<'a> {
    fn seal(
        &self,
        plaintext: &[u8],
        aead_codec: Codec,
        aad: &[u8],
    ) -> Result<(Vec<u8>, Option<Multikey>), Error> {
        if !self.is_public_key() {
            return Err(SealError::NotEncapsulationKey.into());
        }
        if !is_aead_allowed(aead_codec) {
            return Err(SealError::UnsupportedAeadCodec(aead_codec).into());
        }

        let pub_bytes = self.key_bytes()?;
        if pub_bytes.len() != PUB_KEY_LEN {
            return Err(
                SealError::EncapsulationFailed("invalid hybrid public key length".into()).into(),
            );
        }

        // Split public key
        let x25519_pub_arr: [u8; 32] = pub_bytes[..X25519_PUB_LEN]
            .try_into()
            .map_err(|_| SealError::EncapsulationFailed("invalid x25519 public key".into()))?;
        let recipient_x25519_pub = PublicKey::from(x25519_pub_arr);

        let sntrup_ek = EncapsulationKey::try_from(&pub_bytes[X25519_PUB_LEN..])
            .map_err(|_| SealError::EncapsulationFailed("invalid sntrup761 public key".into()))?;

        // X25519: generate ephemeral keypair and ECDH
        let ephemeral_secret = StaticSecret::random_from_rng(&mut rand::rng());
        let ephemeral_pub = PublicKey::from(&ephemeral_secret);
        let ss_x25519 = ephemeral_secret.diffie_hellman(&recipient_x25519_pub);

        // Sntrup761: encapsulate
        let (sntrup_ct, ss_sntrup) = sntrup_ek.encapsulate(&mut OsRng010);

        // Combine shared secrets via BLAKE3
        let combined_ss = combine_shared_secrets(
            ss_sntrup.as_ref(),
            ss_x25519.as_bytes(),
            sntrup_ct.as_ref(),
            ephemeral_pub.as_bytes(),
        );

        // AEAD encrypt
        let (nonce, ct_tag) = aead::aead_seal(aead_codec, &combined_ss, plaintext, aad)?;

        Ok((
            encode_sealed(
                ephemeral_pub.as_bytes(),
                sntrup_ct.as_ref(),
                &nonce,
                &ct_tag,
            ),
            None,
        ))
    }
}

impl<'a> OpenView for View<'a> {
    fn open(
        &self,
        sealed_msg: &[u8],
        _ephemeral: Option<&Multikey>,
        aad: &[u8],
    ) -> Result<Zeroizing<Vec<u8>>, Error> {
        if !self.is_secret_key() {
            return Err(SealError::NotDecapsulationKey.into());
        }

        let (ephemeral_pub_bytes, sntrup_ct_bytes, nonce, ct_tag) = decode_sealed(sealed_msg)?;

        if ephemeral_pub_bytes.len() != X25519_PUB_LEN {
            return Err(
                SealError::InvalidFormat("invalid ephemeral public key length".into()).into(),
            );
        }

        let secret_bytes = {
            let kd = self.mk.data_view()?;
            kd.secret_bytes()?
        };

        if secret_bytes.len() != PRIV_SEED_LEN {
            return Err(
                ConversionsError::SecretKeyFailure("invalid hybrid seed length".into()).into(),
            );
        }

        // X25519 ECDH
        let x25519_seed: [u8; 32] = secret_bytes[..X25519_SEED_LEN]
            .try_into()
            .map_err(|_| SealError::DecapsulationFailed("invalid x25519 seed".into()))?;
        let x25519_secret = StaticSecret::from(x25519_seed);
        let ephemeral_pub_arr: [u8; 32] = ephemeral_pub_bytes
            .as_slice()
            .try_into()
            .map_err(|_| SealError::InvalidFormat("invalid ephemeral public key".into()))?;
        let ephemeral_pub = PublicKey::from(ephemeral_pub_arr);
        let ss_x25519 = x25519_secret.diffie_hellman(&ephemeral_pub);

        // Sntrup761 decapsulate
        let sntrup_seed: [u8; 32] = secret_bytes[X25519_SEED_LEN..PRIV_SEED_LEN]
            .try_into()
            .map_err(|_| SealError::DecapsulationFailed("invalid sntrup761 seed".into()))?;
        let (_ek, dk) = sntrup761::generate_key_deterministic(&sntrup_seed);

        let sntrup_ct = sntrup761::Ciphertext::try_from(sntrup_ct_bytes.as_slice())
            .map_err(|_| SealError::DecapsulationFailed("invalid sntrup761 ciphertext".into()))?;
        let ss_sntrup = dk.decapsulate(&sntrup_ct);

        // Combine shared secrets via BLAKE3
        let combined_ss = combine_shared_secrets(
            ss_sntrup.as_ref(),
            ss_x25519.as_bytes(),
            sntrup_ct_bytes.as_slice(),
            ephemeral_pub_bytes.as_slice(),
        );

        // AEAD decrypt
        Ok(aead::aead_open(
            Codec::Chacha20Poly1305,
            &combined_ss,
            &nonce,
            &ct_tag,
            aad,
        )?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mk::X25519_SNTRUP761_KEY_CODECS;
    use crate::views::Views;

    #[test]
    fn test_key_gen_roundtrip() {
        for codec in X25519_SNTRUP761_KEY_CODECS {
            let mut rng = rand::rng();
            let mk = Builder::new_from_random_bytes(codec, &mut rng)
                .unwrap()
                .with_comment("test hybrid kem key")
                .try_build()
                .unwrap();

            let attr = mk.attr_view().unwrap();
            assert!(attr.is_secret_key());
            assert!(!attr.is_public_key());

            // serialize/deserialize roundtrip
            let bytes: Vec<u8> = mk.clone().into();
            let mk2 = Multikey::try_from(bytes.as_slice()).unwrap();
            assert_eq!(mk, mk2);
        }
    }

    #[test]
    fn test_public_key_derivation() {
        let mut rng = rand::rng();
        let mk = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();

        let conv = mk.conv_view().unwrap();
        let pk = conv.to_public_key().unwrap();

        let attr = pk.attr_view().unwrap();
        assert!(attr.is_public_key());
        assert!(!attr.is_secret_key());

        // derive again => same result
        let pk2 = conv.to_public_key().unwrap();
        assert_eq!(pk, pk2);

        // check public key length
        let dv = pk.data_view().unwrap();
        assert_eq!(dv.key_bytes().unwrap().len(), PUB_KEY_LEN);
    }

    #[test]
    fn test_fingerprint() {
        let mut rng = rand::rng();
        let mk = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();

        let pk = mk.conv_view().unwrap().to_public_key().unwrap();
        let fp = pk
            .fingerprint_view()
            .unwrap()
            .fingerprint(Codec::Sha3256)
            .unwrap();
        let fp_bytes: Vec<u8> = fp.into();
        assert!(!fp_bytes.is_empty());
    }

    #[test]
    fn test_seal_open_roundtrip() {
        let mut rng = rand::rng();
        let sk = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();
        let pk = sk.conv_view().unwrap().to_public_key().unwrap();

        let plaintext = b"hello X25519-sntrup761 hybrid KEM!";
        let (sealed, _) = pk
            .seal_view()
            .unwrap()
            .seal(plaintext, Codec::Chacha20Poly1305, b"")
            .unwrap();

        let opened = sk.open_view().unwrap().open(&sealed, None, b"").unwrap();
        assert_eq!(plaintext.as_slice(), opened.as_slice());
    }

    #[test]
    fn test_wrong_key_fails() {
        let mut rng = rand::rng();
        let sk1 = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();
        let pk1 = sk1.conv_view().unwrap().to_public_key().unwrap();

        let sk2 = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();

        let (sealed, _) = pk1
            .seal_view()
            .unwrap()
            .seal(b"secret data", Codec::Chacha20Poly1305, b"")
            .unwrap();

        assert!(sk2.open_view().unwrap().open(&sealed, None, b"").is_err());
    }

    #[test]
    fn test_seal_requires_public_key() {
        let mut rng = rand::rng();
        let sk = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();

        assert!(sk
            .seal_view()
            .unwrap()
            .seal(b"data", Codec::Chacha20Poly1305, b"")
            .is_err());
    }

    #[test]
    fn test_open_requires_private_key() {
        let mut rng = rand::rng();
        let sk = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();
        let pk = sk.conv_view().unwrap().to_public_key().unwrap();

        let (sealed, _) = pk
            .seal_view()
            .unwrap()
            .seal(b"data", Codec::Chacha20Poly1305, b"")
            .unwrap();

        assert!(pk.open_view().unwrap().open(&sealed, None, b"").is_err());
    }

    #[test]
    fn test_unsupported_aead_codec() {
        let mut rng = rand::rng();
        let sk = Builder::new_from_random_bytes(Codec::X25519Sntrup761Priv, &mut rng)
            .unwrap()
            .try_build()
            .unwrap();
        let pk = sk.conv_view().unwrap().to_public_key().unwrap();

        // Only ChaCha20-Poly1305 is allowed
        assert!(pk
            .seal_view()
            .unwrap()
            .seal(b"data", Codec::AesGcm128, b"")
            .is_err());
        assert!(pk
            .seal_view()
            .unwrap()
            .seal(b"data", Codec::Xchacha20Poly1305, b"")
            .is_err());
    }
}