Skip to main content

proof_crypto/
keys.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Key types + KeyRef strings.
4//! Ed25519: `key:ed25519:<b64u(32B pubkey)>`. P-256: `key:p256:<b64u(64B X||Y)>`.
5
6use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
7use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
8use proof_core::{ErrorCode, ProofError};
9
10use crate::id::b64u_decode;
11
12/// Deterministic Ed25519 key from a 32-byte seed (test vectors use fixed seeds).
13/// Debug is redacted: secret key material must never hit logs (audit P2).
14#[derive(Clone)]
15pub struct Ed25519Key {
16    signing: SigningKey,
17}
18
19impl std::fmt::Debug for Ed25519Key {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        f.write_str("Ed25519Key(redacted)")
22    }
23}
24
25impl Ed25519Key {
26    pub fn from_seed(seed: &[u8; 32]) -> Self {
27        Self {
28            signing: SigningKey::from_bytes(seed),
29        }
30    }
31
32    pub fn pubkey_bytes(&self) -> [u8; 32] {
33        self.signing.verifying_key().to_bytes()
34    }
35
36    pub fn key_ref(&self) -> String {
37        format!(
38            "key:ed25519:{}",
39            URL_SAFE_NO_PAD.encode(self.pubkey_bytes())
40        )
41    }
42
43    pub fn sign(&self, msg: &[u8]) -> [u8; 64] {
44        self.signing.sign(msg).to_bytes()
45    }
46
47    pub fn verifying_key(&self) -> VerifyingKey {
48        self.signing.verifying_key()
49    }
50}
51
52/// Parse `key:ed25519:<b64u>` → 32B pubkey. Rejects wrong prefix/length/alphabet.
53// PE-SEC-005 (canonical keyref shapes).
54pub fn parse_ed25519_keyref(key_ref: &str) -> Result<[u8; 32], ProofError> {
55    let rest = key_ref
56        .strip_prefix("key:ed25519:")
57        .ok_or_else(|| ErrorCode::SchemaViolation.err("issuer must be key:ed25519:<b64u>"))?;
58    let raw = b64u_decode(rest)?;
59    if crate::id::b64u_nopad(&raw) != rest {
60        return Err(ErrorCode::SchemaViolation.err("ed25519 keyref is not canonical base64url"));
61    }
62    if raw.len() != 32 {
63        return Err(ErrorCode::SchemaViolation.err("ed25519 pubkey must be 32 bytes"));
64    }
65    let mut out = [0u8; 32];
66    out.copy_from_slice(&raw);
67    Ok(out)
68}
69
70/// P-256 key (ESP256, optional). Raw pubkey form is 64B X||Y big-endian.
71/// Debug is redacted: secret key material must never hit logs (audit P2).
72#[derive(Clone)]
73pub struct P256Key {
74    signing: p256::ecdsa::SigningKey,
75}
76
77impl std::fmt::Debug for P256Key {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str("P256Key(redacted)")
80    }
81}
82
83impl P256Key {
84    pub fn from_seed(seed: &[u8; 32]) -> Result<Self, ProofError> {
85        let sk = p256::ecdsa::SigningKey::from_bytes(seed.into())
86            .map_err(|e| ErrorCode::Malformed.err(format!("bad p256 seed: {e}")))?;
87        Ok(Self { signing: sk })
88    }
89
90    pub fn pubkey_xy(&self) -> [u8; 64] {
91        let vk = self.signing.verifying_key();
92        let pt = vk.to_encoded_point(false);
93        let x = pt.x().expect("x");
94        let y = pt.y().expect("y");
95        let mut out = [0u8; 64];
96        out[..32].copy_from_slice(x);
97        out[32..].copy_from_slice(y);
98        out
99    }
100
101    pub fn key_ref(&self) -> String {
102        format!("key:p256:{}", URL_SAFE_NO_PAD.encode(self.pubkey_xy()))
103    }
104}
105
106pub fn parse_p256_keyref(key_ref: &str) -> Result<[u8; 64], ProofError> {
107    let rest = key_ref
108        .strip_prefix("key:p256:")
109        .ok_or_else(|| ErrorCode::SchemaViolation.err("issuer must be key:p256:<b64u>"))?;
110    let raw = b64u_decode(rest)?;
111    if crate::id::b64u_nopad(&raw) != rest {
112        return Err(ErrorCode::SchemaViolation.err("p256 keyref is not canonical base64url"));
113    }
114    if raw.len() != 64 {
115        return Err(ErrorCode::SchemaViolation.err("p256 pubkey must be 64 bytes X||Y"));
116    }
117    let mut out = [0u8; 64];
118    out.copy_from_slice(&raw);
119    Ok(out)
120}