Skip to main content

scp_util/
keygen.rs

1use ed25519_zebra::SigningKey;
2use sha2::{Digest, Sha256};
3
4/// Derives an Ed25519 secret key deterministically from `seed`: the key's
5/// 32-byte seed is `SHA-256(seed)`.
6///
7/// The same input always gives the same key and nothing random is added, so
8/// this is neither random key generation nor a password-based derivation: a
9/// short or guessable `seed` gives a guessable key. It is meant for tests and
10/// fixtures. For a production key, pass 32 bytes from a cryptographically
11/// secure random source, or build the `SecretKey` from an Ed25519 key
12/// generated elsewhere (64 bytes: the seed followed by the public key).
13pub fn generate_secret_key(seed: &[u8]) -> thruput_xdr::types::SecretKey {
14    let mut hasher = Sha256::new();
15    hasher.update(seed);
16    let hash = hasher.finalize();
17
18    let secret_bytes: [u8; 32] = hash[..32].try_into().unwrap();
19    let signing_key = SigningKey::from(secret_bytes);
20
21    let mut secret_key_bytes = [0u8; 64];
22    secret_key_bytes[..32].copy_from_slice(&signing_key.to_bytes());
23    secret_key_bytes[32..]
24        .copy_from_slice(&<[u8; 32]>::from(signing_key.verification_key()));
25
26    thruput_xdr::types::SecretKey::Ed25519 {
27        ed25519: thruput_xdr::types::Ed25519SecretKey::from(secret_key_bytes),
28    }
29}
30
31pub fn derive_public_key(
32    secret_key: &thruput_xdr::types::SecretKey,
33) -> thruput_xdr::types::PublicKey {
34    match secret_key {
35        thruput_xdr::types::SecretKey::Ed25519 { ed25519 } => {
36            let secret_bytes: [u8; 32] = ed25519[..32].try_into().unwrap();
37            let public_bytes = <[u8; 32]>::from(
38                SigningKey::from(secret_bytes).verification_key(),
39            );
40
41            thruput_xdr::types::PublicKey::Ed25519 {
42                ed25519: thruput_xdr::types::Ed25519PublicKey::from(
43                    public_bytes,
44                ),
45            }
46        }
47        _ => panic!("Unsupported secret key type"),
48    }
49}
50
51/// The raw bytes of a public key, whatever its scheme.
52pub fn public_key_bytes(public_key: &thruput_xdr::types::PublicKey) -> &[u8] {
53    match public_key {
54        thruput_xdr::types::PublicKey::Ed25519 { ed25519 } => &ed25519[..],
55        thruput_xdr::types::PublicKey::MlDsa65 { mldsa65 } => &mldsa65[..],
56        _ => &[],
57    }
58}
59
60pub fn derive_node_id(
61    sk: &thruput_xdr::types::SecretKey,
62) -> thruput_scp::SCPNodeID {
63    derive_public_key(sk)
64}
65
66/// Parse a SecretKey from a Base64 standard encoded string of the 64-byte secret key
67pub fn parse_secret_key_from_base64(
68    base64_str: &str,
69) -> Result<thruput_xdr::types::SecretKey, String> {
70    use base64::{Engine as _, engine::general_purpose::STANDARD};
71
72    if base64_str.is_empty() {
73        return Err("empty base64 string".to_string());
74    }
75
76    let decoded = STANDARD
77        .decode(base64_str)
78        .map_err(|e| format!("failed to decode base64: {}", e))?;
79
80    if decoded.len() != 64 {
81        return Err(format!("expected 64 bytes, got {}", decoded.len()));
82    }
83
84    let secret_key_bytes: [u8; 64] = decoded
85        .try_into()
86        .map_err(|_| "failed to convert to 64-byte array".to_string())?;
87
88    Ok(thruput_xdr::types::SecretKey::Ed25519 {
89        ed25519: thruput_xdr::types::Ed25519SecretKey::from(secret_key_bytes),
90    })
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    fn secret_bytes(sk: &thruput_xdr::types::SecretKey) -> &[u8; 64] {
98        match sk {
99            thruput_xdr::types::SecretKey::Ed25519 { ed25519 } => ed25519,
100            _ => panic!("unexpected secret key variant"),
101        }
102    }
103
104    fn public_bytes(pk: &thruput_xdr::types::PublicKey) -> &[u8; 32] {
105        match pk {
106            thruput_xdr::types::PublicKey::Ed25519 { ed25519 } => ed25519,
107            _ => panic!("unexpected public key variant"),
108        }
109    }
110
111    #[test]
112    fn public_key_bytes_covers_every_scheme() {
113        let pk = derive_public_key(&generate_secret_key(b"seed-bytes"));
114        assert_eq!(public_key_bytes(&pk), &public_bytes(&pk)[..]);
115        let mldsa65 = thruput_xdr::types::PublicKey::MlDsa65 {
116            mldsa65: Box::new([7u8; 1952].into()),
117        };
118        assert_eq!(public_key_bytes(&mldsa65), &[7u8; 1952][..]);
119    }
120
121    #[test]
122    fn generate_secret_key_is_deterministic() {
123        let sk1 = generate_secret_key(b"seed-a");
124        let sk2 = generate_secret_key(b"seed-a");
125        assert_eq!(secret_bytes(&sk1), secret_bytes(&sk2));
126    }
127
128    #[test]
129    fn generate_secret_key_differs_for_different_seeds() {
130        let sk1 = generate_secret_key(b"seed-a");
131        let sk2 = generate_secret_key(b"seed-b");
132        assert_ne!(secret_bytes(&sk1), secret_bytes(&sk2));
133    }
134
135    #[test]
136    fn generate_secret_key_embeds_matching_public_key() {
137        let sk = generate_secret_key(b"seed-roundtrip");
138        let pk = derive_public_key(&sk);
139        let sk_bytes = secret_bytes(&sk);
140        let pk_bytes = public_bytes(&pk);
141        assert_eq!(&sk_bytes[32..], &pk_bytes[..]);
142    }
143
144    #[test]
145    fn derive_public_key_is_deterministic() {
146        let sk = generate_secret_key(b"seed-derive");
147        let pk1 = derive_public_key(&sk);
148        let pk2 = derive_public_key(&sk);
149        assert_eq!(public_bytes(&pk1), public_bytes(&pk2));
150    }
151
152    #[test]
153    fn derive_public_key_differs_for_different_secrets() {
154        let sk1 = generate_secret_key(b"seed-a");
155        let sk2 = generate_secret_key(b"seed-b");
156        assert_ne!(
157            public_bytes(&derive_public_key(&sk1)),
158            public_bytes(&derive_public_key(&sk2)),
159        );
160    }
161
162    #[test]
163    fn derive_node_id_matches_derive_public_key() {
164        let sk = generate_secret_key(b"seed-node-id");
165        let pk = derive_public_key(&sk);
166        let node_id = derive_node_id(&sk);
167        assert_eq!(public_bytes(&pk), public_bytes(&node_id));
168    }
169}