affinidi-crypto 0.2.0

Cryptographic primitives and JWK types for Affinidi TDK
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
//! Key-agreement curves and keys for JOSE ECDH (X25519, P-256, K-256).
//!
//! Ported from `affinidi-messaging-didcomm` for the #327 centralization.
//! Curve-polymorphic key material is necessarily runtime-dispatched (a
//! DIDComm message selects its curve at runtime), so the public/private
//! keys are enums. Extensibility is preserved by locality: adding a curve
//! is a new variant plus its arms **here only** — every derivation, KDF,
//! key-wrap, and content-encryption path is curve-agnostic (it operates on
//! the raw shared-secret bytes `diffie_hellman` returns), so none of them
//! change. The `Curve` enum doubles as the typed JOSE `crv` wire boundary.

use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use rand_core::OsRng;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::error::CryptoError;

/// Supported key-agreement curves (JOSE `crv` identifiers).
// `#[non_exhaustive]`: adding a new key-agreement curve must be a
// non-breaking change for downstream crates, so external matches always
// carry a wildcard arm. The break for this attribute was taken once, in the
// 0.2.0 release that introduced P-384/P-521.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Curve {
    X25519,
    P256,
    K256,
    P384,
    P521,
}

impl Curve {
    /// JWK `crv` value for this curve.
    pub fn jwk_crv(&self) -> &'static str {
        match self {
            Curve::X25519 => "X25519",
            Curve::P256 => "P-256",
            Curve::K256 => "secp256k1",
            Curve::P384 => "P-384",
            Curve::P521 => "P-521",
        }
    }
}

/// A public key for key agreement (any supported curve).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PublicKeyAgreement {
    X25519([u8; 32]),
    P256(p256::PublicKey),
    K256(k256::PublicKey),
    P384(p384::PublicKey),
    P521(p521::PublicKey),
}

impl PublicKeyAgreement {
    /// The curve of this key.
    pub fn curve(&self) -> Curve {
        match self {
            PublicKeyAgreement::X25519(_) => Curve::X25519,
            PublicKeyAgreement::P256(_) => Curve::P256,
            PublicKeyAgreement::K256(_) => Curve::K256,
            PublicKeyAgreement::P384(_) => Curve::P384,
            PublicKeyAgreement::P521(_) => Curve::P521,
        }
    }

    /// Encode as a JWK JSON value.
    pub fn to_jwk(&self) -> Value {
        match self {
            PublicKeyAgreement::X25519(bytes) => serde_json::json!({
                "kty": "OKP",
                "crv": "X25519",
                "x": URL_SAFE_NO_PAD.encode(bytes),
            }),
            PublicKeyAgreement::P256(pk) => {
                use p256::elliptic_curve::sec1::ToEncodedPoint;
                let point = pk.to_encoded_point(false);
                serde_json::json!({
                    "kty": "EC",
                    "crv": "P-256",
                    "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
                    "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
                })
            }
            PublicKeyAgreement::K256(pk) => {
                use k256::elliptic_curve::sec1::ToEncodedPoint;
                let point = pk.to_encoded_point(false);
                serde_json::json!({
                    "kty": "EC",
                    "crv": "secp256k1",
                    "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
                    "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
                })
            }
            PublicKeyAgreement::P384(pk) => {
                use p384::elliptic_curve::sec1::ToEncodedPoint;
                let point = pk.to_encoded_point(false);
                serde_json::json!({
                    "kty": "EC",
                    "crv": "P-384",
                    "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
                    "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
                })
            }
            PublicKeyAgreement::P521(pk) => {
                use p521::elliptic_curve::sec1::ToEncodedPoint;
                let point = pk.to_encoded_point(false);
                serde_json::json!({
                    "kty": "EC",
                    "crv": "P-521",
                    "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
                    "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
                })
            }
        }
    }

    /// Raw public-key bytes for storage/transport: the 32-byte key for
    /// X25519, or the **compressed** SEC1 point for the EC curves. Curve
    /// dispatch lives here (alongside every other curve arm) so callers do
    /// not match on the enum themselves.
    pub fn to_public_bytes(&self) -> Vec<u8> {
        match self {
            PublicKeyAgreement::X25519(bytes) => bytes.to_vec(),
            PublicKeyAgreement::P256(pk) => {
                use p256::elliptic_curve::sec1::ToEncodedPoint;
                pk.to_encoded_point(true).as_bytes().to_vec()
            }
            PublicKeyAgreement::K256(pk) => {
                use k256::elliptic_curve::sec1::ToEncodedPoint;
                pk.to_encoded_point(true).as_bytes().to_vec()
            }
            PublicKeyAgreement::P384(pk) => {
                use p384::elliptic_curve::sec1::ToEncodedPoint;
                pk.to_encoded_point(true).as_bytes().to_vec()
            }
            PublicKeyAgreement::P521(pk) => {
                use p521::elliptic_curve::sec1::ToEncodedPoint;
                pk.to_encoded_point(true).as_bytes().to_vec()
            }
        }
    }

    /// Construct from raw bytes and a known curve.
    ///
    /// For X25519: expects 32 bytes. For P-256/K-256: expects a SEC1
    /// encoded point (compressed or uncompressed).
    pub fn from_raw_bytes(curve: Curve, bytes: &[u8]) -> Result<Self, CryptoError> {
        match curve {
            Curve::X25519 => {
                let arr: [u8; 32] = bytes.try_into().map_err(|_| {
                    CryptoError::KeyAgreement("X25519 public key must be 32 bytes".into())
                })?;
                Ok(PublicKeyAgreement::X25519(arr))
            }
            Curve::P256 => {
                let pk = p256::PublicKey::from_sec1_bytes(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid P-256 public key: {e}"))
                })?;
                Ok(PublicKeyAgreement::P256(pk))
            }
            Curve::K256 => {
                let pk = k256::PublicKey::from_sec1_bytes(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid K-256 public key: {e}"))
                })?;
                Ok(PublicKeyAgreement::K256(pk))
            }
            Curve::P384 => {
                let pk = p384::PublicKey::from_sec1_bytes(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid P-384 public key: {e}"))
                })?;
                Ok(PublicKeyAgreement::P384(pk))
            }
            Curve::P521 => {
                let pk = p521::PublicKey::from_sec1_bytes(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid P-521 public key: {e}"))
                })?;
                Ok(PublicKeyAgreement::P521(pk))
            }
        }
    }

    /// Parse from a JWK JSON value.
    pub fn from_jwk(jwk: &Value) -> Result<Self, CryptoError> {
        let crv = jwk["crv"]
            .as_str()
            .ok_or_else(|| CryptoError::KeyAgreement("missing crv in JWK".into()))?;

        match crv {
            "X25519" => {
                let x = jwk["x"]
                    .as_str()
                    .ok_or_else(|| CryptoError::KeyAgreement("missing x in X25519 JWK".into()))?;
                let bytes = URL_SAFE_NO_PAD
                    .decode(x)
                    .map_err(|e| CryptoError::KeyAgreement(format!("invalid x: {e}")))?;
                let arr: [u8; 32] = bytes
                    .try_into()
                    .map_err(|_| CryptoError::KeyAgreement("X25519 key must be 32 bytes".into()))?;
                Ok(PublicKeyAgreement::X25519(arr))
            }
            "P-256" => {
                let point = ec_point_from_jwk(jwk)?;
                let pk = p256::PublicKey::from_sec1_bytes(&point)
                    .map_err(|e| CryptoError::KeyAgreement(format!("invalid P-256 key: {e}")))?;
                Ok(PublicKeyAgreement::P256(pk))
            }
            "secp256k1" => {
                let point = ec_point_from_jwk(jwk)?;
                let pk = k256::PublicKey::from_sec1_bytes(&point)
                    .map_err(|e| CryptoError::KeyAgreement(format!("invalid K-256 key: {e}")))?;
                Ok(PublicKeyAgreement::K256(pk))
            }
            "P-384" => {
                let point = ec_point_from_jwk(jwk)?;
                let pk = p384::PublicKey::from_sec1_bytes(&point)
                    .map_err(|e| CryptoError::KeyAgreement(format!("invalid P-384 key: {e}")))?;
                Ok(PublicKeyAgreement::P384(pk))
            }
            "P-521" => {
                let point = ec_point_from_jwk(jwk)?;
                let pk = p521::PublicKey::from_sec1_bytes(&point)
                    .map_err(|e| CryptoError::KeyAgreement(format!("invalid P-521 key: {e}")))?;
                Ok(PublicKeyAgreement::P521(pk))
            }
            other => Err(CryptoError::UnsupportedKeyType(format!(
                "unsupported key-agreement curve: {other}"
            ))),
        }
    }
}

/// Build an uncompressed SEC1 point (`0x04 || x || y`) from a JWK's `x`/`y`.
fn ec_point_from_jwk(jwk: &Value) -> Result<Vec<u8>, CryptoError> {
    let x = jwk["x"]
        .as_str()
        .ok_or_else(|| CryptoError::KeyAgreement("missing x in EC JWK".into()))?;
    let y = jwk["y"]
        .as_str()
        .ok_or_else(|| CryptoError::KeyAgreement("missing y in EC JWK".into()))?;
    let x_bytes = URL_SAFE_NO_PAD
        .decode(x)
        .map_err(|e| CryptoError::KeyAgreement(format!("invalid x: {e}")))?;
    let y_bytes = URL_SAFE_NO_PAD
        .decode(y)
        .map_err(|e| CryptoError::KeyAgreement(format!("invalid y: {e}")))?;
    let mut point = Vec::with_capacity(1 + x_bytes.len() + y_bytes.len());
    point.push(0x04);
    point.extend_from_slice(&x_bytes);
    point.extend_from_slice(&y_bytes);
    Ok(point)
}

/// A private key for key agreement (any supported curve).
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
#[non_exhaustive]
pub enum PrivateKeyAgreement {
    X25519(#[zeroize(skip)] x25519_dalek::StaticSecret),
    P256(#[zeroize(skip)] p256::SecretKey),
    K256(#[zeroize(skip)] k256::SecretKey),
    P384(#[zeroize(skip)] p384::SecretKey),
    P521(#[zeroize(skip)] p521::SecretKey),
}

impl std::fmt::Debug for PrivateKeyAgreement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PrivateKeyAgreement::X25519(_) => write!(f, "PrivateKeyAgreement::X25519([REDACTED])"),
            PrivateKeyAgreement::P256(_) => write!(f, "PrivateKeyAgreement::P256([REDACTED])"),
            PrivateKeyAgreement::K256(_) => write!(f, "PrivateKeyAgreement::K256([REDACTED])"),
            PrivateKeyAgreement::P384(_) => write!(f, "PrivateKeyAgreement::P384([REDACTED])"),
            PrivateKeyAgreement::P521(_) => write!(f, "PrivateKeyAgreement::P521([REDACTED])"),
        }
    }
}

impl PrivateKeyAgreement {
    /// Construct from raw private key bytes and a known curve.
    ///
    /// For X25519: expects 32 bytes (clamped scalar). For P-256/K-256:
    /// expects the scalar bytes.
    pub fn from_raw_bytes(curve: Curve, bytes: &[u8]) -> Result<Self, CryptoError> {
        match curve {
            Curve::X25519 => {
                let arr: [u8; 32] = bytes.try_into().map_err(|_| {
                    CryptoError::KeyAgreement("X25519 private key must be 32 bytes".into())
                })?;
                Ok(PrivateKeyAgreement::X25519(
                    x25519_dalek::StaticSecret::from(arr),
                ))
            }
            Curve::P256 => {
                let sk = p256::SecretKey::from_slice(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid P-256 private key: {e}"))
                })?;
                Ok(PrivateKeyAgreement::P256(sk))
            }
            Curve::K256 => {
                let sk = k256::SecretKey::from_slice(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid K-256 private key: {e}"))
                })?;
                Ok(PrivateKeyAgreement::K256(sk))
            }
            Curve::P384 => {
                let sk = p384::SecretKey::from_slice(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid P-384 private key: {e}"))
                })?;
                Ok(PrivateKeyAgreement::P384(sk))
            }
            Curve::P521 => {
                let sk = p521::SecretKey::from_slice(bytes).map_err(|e| {
                    CryptoError::KeyAgreement(format!("invalid P-521 private key: {e}"))
                })?;
                Ok(PrivateKeyAgreement::P521(sk))
            }
        }
    }

    /// Generate a new random private key on the given curve.
    pub fn generate(curve: Curve) -> Self {
        match curve {
            Curve::X25519 => {
                PrivateKeyAgreement::X25519(x25519_dalek::StaticSecret::random_from_rng(OsRng))
            }
            Curve::P256 => PrivateKeyAgreement::P256(p256::SecretKey::random(&mut OsRng)),
            Curve::K256 => PrivateKeyAgreement::K256(k256::SecretKey::random(&mut OsRng)),
            Curve::P384 => PrivateKeyAgreement::P384(p384::SecretKey::random(&mut OsRng)),
            Curve::P521 => PrivateKeyAgreement::P521(p521::SecretKey::random(&mut OsRng)),
        }
    }

    /// Derive the public key.
    pub fn public_key(&self) -> PublicKeyAgreement {
        match self {
            PrivateKeyAgreement::X25519(sk) => {
                PublicKeyAgreement::X25519(x25519_dalek::PublicKey::from(sk).to_bytes())
            }
            PrivateKeyAgreement::P256(sk) => PublicKeyAgreement::P256(sk.public_key()),
            PrivateKeyAgreement::K256(sk) => PublicKeyAgreement::K256(sk.public_key()),
            PrivateKeyAgreement::P384(sk) => PublicKeyAgreement::P384(sk.public_key()),
            PrivateKeyAgreement::P521(sk) => PublicKeyAgreement::P521(sk.public_key()),
        }
    }

    /// The curve of this key.
    pub fn curve(&self) -> Curve {
        match self {
            PrivateKeyAgreement::X25519(_) => Curve::X25519,
            PrivateKeyAgreement::P256(_) => Curve::P256,
            PrivateKeyAgreement::K256(_) => Curve::K256,
            PrivateKeyAgreement::P384(_) => Curve::P384,
            PrivateKeyAgreement::P521(_) => Curve::P521,
        }
    }

    /// Perform ECDH with a public key, returning the raw shared-secret bytes.
    pub fn diffie_hellman(
        &self,
        their_public: &PublicKeyAgreement,
    ) -> Result<Vec<u8>, CryptoError> {
        match (self, their_public) {
            (PrivateKeyAgreement::X25519(sk), PublicKeyAgreement::X25519(pk)) => {
                let pk = x25519_dalek::PublicKey::from(*pk);
                Ok(sk.diffie_hellman(&pk).as_bytes().to_vec())
            }
            (PrivateKeyAgreement::P256(sk), PublicKeyAgreement::P256(pk)) => {
                use p256::ecdh::diffie_hellman;
                let shared = diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
                Ok(shared.raw_secret_bytes().to_vec())
            }
            (PrivateKeyAgreement::K256(sk), PublicKeyAgreement::K256(pk)) => {
                use k256::ecdh::diffie_hellman;
                let shared = diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
                Ok(shared.raw_secret_bytes().to_vec())
            }
            (PrivateKeyAgreement::P384(sk), PublicKeyAgreement::P384(pk)) => {
                use p384::ecdh::diffie_hellman;
                let shared = diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
                Ok(shared.raw_secret_bytes().to_vec())
            }
            (PrivateKeyAgreement::P521(sk), PublicKeyAgreement::P521(pk)) => {
                use p521::ecdh::diffie_hellman;
                let shared = diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
                Ok(shared.raw_secret_bytes().to_vec())
            }
            _ => Err(CryptoError::KeyAgreement(
                "curve mismatch between private and public keys".into(),
            )),
        }
    }
}

/// An ephemeral key pair for ECDH (generated per-message).
pub struct EphemeralKeyPair {
    pub private: PrivateKeyAgreement,
    pub public: PublicKeyAgreement,
}

impl EphemeralKeyPair {
    /// Generate a new ephemeral key pair on the given curve.
    pub fn generate(curve: Curve) -> Self {
        let private = PrivateKeyAgreement::generate(curve);
        let public = private.public_key();
        Self { private, public }
    }
}