hiss 0.1.0

Static, type-level Noise Protocol Framework with pluggable hardware-backed crypto.
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
//! Ed25519 signing and key exchange.
//!
//! Ed25519 is used for signing message headers — where the signature
//! can double as a `message_id` — and, via the birational equivalence
//! between Edwards and Montgomery forms, for Diffie–Hellman key
//! exchange.
//!
//! This module implements the [`Curve`] trait for Ed25519; the provider
//! backends that perform its operations live in [`crate::provider`].
//!
//! # Backends
//!
//! * **Software** ([`SoftwareEd25519PrivateKey`], always available) —
//!   pure-Rust implementation using `cryptoxide`. Suitable for tests,
//!   WASM, and any platform without native Ed25519 support.
//!
//! * **Apple** (iOS/macOS) — Ed25519 is still **software**-signed (the
//!   Secure Enclave has no Ed25519 support), but the 32-byte seed is
//!   sealed at rest to the device's Secure Enclave P-256 key. See
//!   `AppleSecureEnclave`.
//!
//! Both backends share the same [`Ed25519PublicKey`] and
//! [`Ed25519Signature`] types, and both produce RFC 8032-compliant
//! deterministic signatures.
//!
//! # Determinism
//!
//! Ed25519 signatures are deterministic per RFC 8032 — the same
//! input always produces the same signature. This is critical
//! because `message_id = signature`, so non-deterministic signatures
//! would produce non-reproducible message identifiers.
//!
//! # Key exchange
//!
//! DH is performed by converting Ed25519 keys to their Curve25519
//! (Montgomery) equivalents via `cryptoxide::ed25519::exchange`.
//! The shared secret is 32 bytes — the x-coordinate of the shared
//! point on Curve25519.
//!
//! This Ed25519 DH is a **standalone** capability over Ed25519 keys; it
//! is **not** the Noise `25519` DH function. A Noise handshake that wants
//! Curve25519 key agreement must use [`X25519`](super::x25519::X25519),
//! whose public keys are bare Montgomery u-coordinates and interoperate
//! byte-for-byte with other Noise implementations. The two are **not**
//! wire-compatible — an Edwards-point encoding here versus a Montgomery
//! u-coordinate there.

use std::fmt;

use cryptoxide::ed25519 as ed;
use packtool::Packed;
use rand_core::{CryptoRng, RngCore};

use super::{Curve, DhCurve, SharedSecret, SigningCurve};

// ── Errors ─────────────────────────────────────────────────────

/// Errors produced by the Ed25519 signing and DH curve.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// A public-key byte string was not the expected 32 bytes; the wrapped
    /// value is the length supplied.
    #[error("invalid public key length: expected 32 bytes, got {0}")]
    InvalidPublicKeyLength(usize),
    /// A signature byte string was not the expected 64 bytes; the wrapped
    /// value is the length supplied.
    #[error("invalid signature length: expected 64 bytes, got {0}")]
    InvalidSignatureLength(usize),
    /// A platform entropy/key operation failed (Apple `SecRandom` seed path).
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    #[error("{0}")]
    Platform(String),
}

// ── Curve marker ───────────────────────────────────────────────

/// Ed25519 curve marker.
///
/// Zero-sized type implementing [`Curve`] that ties together the
/// concrete [`Ed25519PublicKey`], [`Ed25519Signature`], and
/// [`SharedSecret`] types. Used as a type parameter for
/// [`DhProviderAsync`](crate::provider::DhProviderAsync).
#[derive(Debug, Clone, Copy, Default)]
pub struct Ed25519;

impl Curve for Ed25519 {
    const NAME: &'static str = "Ed25519";
    const PUBLIC_KEY_SIZE: usize = 32;
    const PRIVATE_KEY_SIZE: usize = 32;

    type Error = Error;
    type PublicKey = Ed25519PublicKey;

    fn public_key_from_bytes(bytes: &[u8]) -> Result<Self::PublicKey, Self::Error> {
        Ed25519PublicKey::from_bytes(bytes)
    }
}

impl DhCurve for Ed25519 {
    const DHLEN: usize = 32;
    type SharedSecret = SharedSecret<32>;
}

impl SigningCurve for Ed25519 {
    type Signature = Ed25519Signature;
}

// ── Public key ─────────────────────────────────────────────────

/// An Ed25519 public key (32 bytes).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Packed)]
pub struct Ed25519PublicKey(#[packed(accessor = false)] [u8; 32]);

impl Ed25519PublicKey {
    /// Construct from a 32-byte slice.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        let arr: [u8; 32] = bytes
            .try_into()
            .map_err(|_| Error::InvalidPublicKeyLength(bytes.len()))?;
        Ok(Self(arr))
    }

    /// Return the raw 32 bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Verify an Ed25519 signature over `message`.
    pub fn verify(&self, signature: Ed25519Signature, message: impl AsRef<[u8]>) -> bool {
        ed::verify(message.as_ref(), &self.0, &signature.0)
    }
}

impl AsRef<[u8]> for Ed25519PublicKey {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Display for Ed25519PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&hex::encode(self.0))
    }
}

impl fmt::Debug for Ed25519PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&hex::encode(self.0))
    }
}

// ── Signature ──────────────────────────────────────────────────

/// An Ed25519 signature (64 bytes).
///
/// When a signature doubles as a message identifier, it is
/// unforgeable, deterministic (RFC 8032), and self-verifying.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Packed)]
pub struct Ed25519Signature(#[packed(accessor = false)] [u8; 64]);

impl Ed25519Signature {
    /// Construct from a 64-byte slice.
    pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        let arr: [u8; 64] = bytes
            .try_into()
            .map_err(|_| Error::InvalidSignatureLength(bytes.len()))?;
        Ok(Self(arr))
    }

    /// Return the raw 64 bytes.
    pub fn as_bytes(&self) -> &[u8; 64] {
        &self.0
    }
}

impl AsRef<[u8]> for Ed25519Signature {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Display for Ed25519Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&hex::encode(self.0))
    }
}

impl fmt::Debug for Ed25519Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&hex::encode(self.0))
    }
}

// ── Software private key ───────────────────────────────────────

/// Software Ed25519 private key (32-byte seed + cached keypair).
///
/// The seed is expanded internally by `cryptoxide` per RFC 8032
/// when signing. Both the seed and cached keypair are zeroised on
/// drop.
///
/// This is the software backend — always available, and the only
/// Ed25519 backend; on Apple platforms its seed is sealed at rest to
/// the Secure Enclave P-256 key (see
/// `AppleSecureEnclave`).
pub struct SoftwareEd25519PrivateKey {
    /// The 32-byte seed.
    seed: [u8; 32],
    /// The 64-byte keypair (seed ‖ public key) cached for signing.
    keypair: [u8; 64],
}

impl SoftwareEd25519PrivateKey {
    /// Generate a new random Ed25519 key pair.
    ///
    /// The caller supplies the RNG, which must be cryptographically
    /// secure. This makes generation compatible with platform-provided
    /// CSPRNGs and allows reproducible tests with a seeded RNG.
    pub fn generate<R: RngCore + CryptoRng>(mut rng: R) -> Self {
        let mut seed = [0u8; 32];
        rng.fill_bytes(&mut seed);
        Self::from_seed(seed)
    }

    /// Construct from a known 32-byte seed.
    ///
    /// Useful for testing with deterministic keys or for restoring
    /// a key from storage.
    pub fn from_seed(seed: [u8; 32]) -> Self {
        let (keypair, _public) = ed::keypair(&seed);
        Self { seed, keypair }
    }

    /// Return the corresponding public key.
    pub fn public_key(&self) -> Ed25519PublicKey {
        let pk_bytes: [u8; 32] = self.keypair[32..64].try_into().unwrap();
        Ed25519PublicKey(pk_bytes)
    }

    /// Sign `message` with this key. Deterministic per RFC 8032.
    pub fn sign(&self, message: &[u8]) -> Ed25519Signature {
        Ed25519Signature(ed::signature(message, &self.keypair))
    }

    /// Perform Diffie–Hellman key exchange with a peer's public key.
    ///
    /// Converts Ed25519 keys to their Curve25519 (Montgomery)
    /// equivalents via `cryptoxide::ed25519::exchange`.
    pub fn dh(&self, peer: &Ed25519PublicKey) -> SharedSecret<32> {
        SharedSecret::new(ed::exchange(&peer.0, &self.seed))
    }

    /// Return the raw 32-byte seed.
    ///
    /// Use with care — this is secret material. Intended for
    /// persisting the key to storage (Keychain, sealed blob, etc.).
    pub fn seed(&self) -> &[u8; 32] {
        &self.seed
    }
}

impl Drop for SoftwareEd25519PrivateKey {
    fn drop(&mut self) {
        crate::zeroize::zeroize_array(&mut self.seed);
        crate::zeroize::zeroize_array(&mut self.keypair);
    }
}

#[cfg(not(test))]
impl fmt::Debug for SoftwareEd25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SoftwareEd25519PrivateKey")
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
impl fmt::Debug for SoftwareEd25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SoftwareEd25519PrivateKey")
            .field("seed", &hex::encode(self.seed))
            .finish()
    }
}

// ── Tests ──────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::provider::{
        CryptoKeyProviderAsync, DhProviderAsync, EphemeralOnly, ProviderExt, SigningProviderAsync,
    };
    use rand::{SeedableRng, rngs::StdRng};

    // ── Direct API tests ─────────────────────────────────────────

    #[test]
    fn generate_and_sign_verify() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk = sk.public_key();
        let msg = b"Hello hiss";

        let sig = sk.sign(msg);
        assert!(pk.verify(sig, msg));
    }

    #[test]
    fn deterministic_signatures() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let msg = b"determinism matters";

        let sig1 = sk.sign(msg);
        let sig2 = sk.sign(msg);
        assert_eq!(
            sig1, sig2,
            "Ed25519 signatures must be deterministic (RFC 8032)"
        );
    }

    #[test]
    fn wrong_message_fails_verification() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk = sk.public_key();

        let sig = sk.sign(b"correct message");
        assert!(!pk.verify(sig, b"wrong message"));
    }

    #[test]
    fn wrong_key_fails_verification() {
        let sk1 = SoftwareEd25519PrivateKey::generate(rand::rng());
        let sk2 = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk2 = sk2.public_key();

        let sig = sk1.sign(b"signed by sk1");
        assert!(!pk2.verify(sig, b"signed by sk1"));
    }

    #[test]
    fn corrupted_signature_fails() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk = sk.public_key();
        let sig = sk.sign(b"test");

        let mut raw = *sig.as_bytes();
        raw[16] ^= 0xFF;
        let corrupted = Ed25519Signature::try_from_bytes(&raw).unwrap();

        assert!(!pk.verify(corrupted, b"test"));
    }

    #[test]
    fn zero_signature_fails() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk = sk.public_key();

        let zero_sig = Ed25519Signature::try_from_bytes(&[0u8; 64]).unwrap();
        assert!(!pk.verify(zero_sig, b"anything"));
    }

    #[test]
    fn public_key_round_trip() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk = sk.public_key();

        let pk2 = Ed25519PublicKey::from_bytes(pk.as_bytes()).unwrap();
        assert_eq!(pk, pk2);
    }

    #[test]
    fn public_key_wrong_length_rejected() {
        let err = Ed25519PublicKey::from_bytes(&[0u8; 31]).unwrap_err();
        assert!(matches!(err, Error::InvalidPublicKeyLength(31)));

        let err = Ed25519PublicKey::from_bytes(&[0u8; 33]).unwrap_err();
        assert!(matches!(err, Error::InvalidPublicKeyLength(33)));
    }

    #[test]
    fn signature_wrong_length_rejected() {
        let err = Ed25519Signature::try_from_bytes(&[0u8; 63]).unwrap_err();
        assert!(matches!(err, Error::InvalidSignatureLength(63)));

        let err = Ed25519Signature::try_from_bytes(&[0u8; 65]).unwrap_err();
        assert!(matches!(err, Error::InvalidSignatureLength(65)));
    }

    #[test]
    fn from_seed_is_deterministic() {
        let seed = [42u8; 32];
        let sk1 = SoftwareEd25519PrivateKey::from_seed(seed);
        let sk2 = SoftwareEd25519PrivateKey::from_seed(seed);

        assert_eq!(sk1.public_key(), sk2.public_key());

        let sig1 = sk1.sign(b"same seed same key");
        let sig2 = sk2.sign(b"same seed same key");
        assert_eq!(sig1, sig2);
    }

    #[test]
    fn different_seeds_produce_different_keys() {
        let sk1 = SoftwareEd25519PrivateKey::from_seed([1u8; 32]);
        let sk2 = SoftwareEd25519PrivateKey::from_seed([2u8; 32]);

        assert_ne!(sk1.public_key(), sk2.public_key());
    }

    // ── DH tests ─────────────────────────────────────────────────

    #[test]
    fn dh_is_symmetric() {
        let sk1 = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk1 = sk1.public_key();
        let sk2 = SoftwareEd25519PrivateKey::generate(rand::rng());
        let pk2 = sk2.public_key();

        let ss1 = sk1.dh(&pk2);
        let ss2 = sk2.dh(&pk1);
        assert_eq!(ss1, ss2);
    }

    #[test]
    fn dh_different_peers_produce_different_secrets() {
        let sk = SoftwareEd25519PrivateKey::generate(rand::rng());
        let peer1 = SoftwareEd25519PrivateKey::generate(rand::rng()).public_key();
        let peer2 = SoftwareEd25519PrivateKey::generate(rand::rng()).public_key();

        let ss1 = sk.dh(&peer1);
        let ss2 = sk.dh(&peer2);
        assert_ne!(ss1, ss2);
    }

    // ── DhProviderAsync trait tests ───────────────────────────────

    #[tokio::test]
    async fn provider_sign_and_dh() {
        let mut provider = EphemeralOnly::new(StdRng::from_os_rng());

        let sk1 = CryptoKeyProviderAsync::<Ed25519>::generate_static_key_async(&mut provider)
            .await
            .unwrap();
        let pk1 = provider.public(&sk1).unwrap();

        let sk2 = CryptoKeyProviderAsync::<Ed25519>::generate_ephemeral_key_async(&mut provider)
            .await
            .unwrap();
        let pk2 = provider.public(&sk2).unwrap();

        // Sign and verify
        const MSG: &[u8] = b"hello hiss";
        let sig = SigningProviderAsync::<Ed25519>::sign_async(&provider, &sk1, MSG)
            .await
            .unwrap();
        assert!(pk1.verify(sig, MSG));
        assert!(!pk2.verify(sig, MSG));

        // DH symmetry
        let ss1 = DhProviderAsync::<Ed25519>::dh_async(&provider, &sk1, &pk2)
            .await
            .unwrap();
        let ss2 = DhProviderAsync::<Ed25519>::dh_async(&provider, &sk2, &pk1)
            .await
            .unwrap();
        assert_eq!(ss1, ss2);
    }
}