Skip to main content

keep_core/
keys.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Key types and Nostr keypair operations.
5use bech32::{Bech32, Hrp};
6use k256::schnorr::SigningKey;
7use serde::{Deserialize, Serialize};
8use zeroize::Zeroize;
9
10use crate::crypto::{self, MlockedBox};
11use crate::error::{CryptoError, KeepError, Result};
12
13/// The type of key stored in Keep.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub enum KeyType {
16    /// A Nostr secp256k1 keypair.
17    Nostr,
18    /// A Bitcoin key (reserved for future use).
19    Bitcoin,
20    /// A FROST threshold signature share.
21    FrostShare,
22}
23
24/// A Nostr keypair with memory-locked secret key.
25///
26/// # Example
27///
28/// ```
29/// use keep_core::keys::NostrKeypair;
30///
31/// let keypair = NostrKeypair::generate()?;
32/// println!("npub: {}", keypair.to_npub());
33/// println!("nsec: {}", keypair.to_nsec());
34///
35/// let signature = keypair.sign(b"hello nostr")?;
36/// # Ok::<(), keep_core::error::KeepError>(())
37/// ```
38pub struct NostrKeypair {
39    secret_key: MlockedBox<32>,
40    public_key: [u8; 32],
41}
42
43impl NostrKeypair {
44    /// Generate a new random keypair.
45    pub fn generate() -> Result<Self> {
46        const MAX_RETRIES: usize = 64;
47        for _ in 0..MAX_RETRIES {
48            let mut secret_bytes: [u8; 32] = crypto::try_random_bytes()?;
49            if let Ok(signing_key) = SigningKey::from_bytes(&secret_bytes) {
50                let verifying_key = signing_key.verifying_key();
51                return Ok(Self {
52                    secret_key: MlockedBox::new(&mut secret_bytes),
53                    public_key: verifying_key.to_bytes().into(),
54                });
55            }
56            secret_bytes.zeroize();
57        }
58        Err(CryptoError::invalid_key("failed to generate valid keypair after 64 attempts").into())
59    }
60
61    /// Create a keypair from secret bytes. Zeroes the source.
62    pub fn from_secret_bytes(secret: &mut [u8; 32]) -> Result<Self> {
63        let signing_key = SigningKey::from_bytes(secret)
64            .map_err(|_| CryptoError::invalid_key("invalid secret key"))?;
65        let verifying_key = signing_key.verifying_key();
66
67        Ok(Self {
68            secret_key: MlockedBox::new(secret),
69            public_key: verifying_key.to_bytes().into(),
70        })
71    }
72
73    /// Create a keypair from a bech32 nsec string.
74    ///
75    /// # Example
76    ///
77    /// ```
78    /// use keep_core::keys::NostrKeypair;
79    ///
80    /// let keypair = NostrKeypair::generate()?;
81    /// let nsec = keypair.to_nsec();
82    ///
83    /// let restored = NostrKeypair::from_nsec(&nsec)?;
84    /// assert_eq!(keypair.public_bytes(), restored.public_bytes());
85    /// # Ok::<(), keep_core::error::KeepError>(())
86    /// ```
87    ///
88    /// # Errors
89    ///
90    /// Returns [`KeepError::InvalidNsec`] if the string is not a valid nsec.
91    pub fn from_nsec(nsec: &str) -> Result<Self> {
92        let (hrp, mut data) = bech32::decode(nsec).map_err(|_| KeepError::InvalidNsec)?;
93
94        if hrp.as_str() != "nsec" {
95            data.zeroize();
96            return Err(KeepError::InvalidNsec);
97        }
98
99        if data.len() != 32 {
100            data.zeroize();
101            return Err(KeepError::InvalidNsec);
102        }
103
104        let mut secret = [0u8; 32];
105        secret.copy_from_slice(&data);
106        data.zeroize();
107        Self::from_secret_bytes(&mut secret)
108    }
109
110    /// Export as a bech32 nsec string.
111    pub fn to_nsec(&self) -> String {
112        const NSEC_HRP: Hrp = Hrp::parse_unchecked("nsec");
113        bech32::encode::<Bech32>(NSEC_HRP, &*self.secret_key)
114            .expect("bech32 encode of 32-byte secret with valid HRP is infallible")
115    }
116
117    /// Export as a bech32 npub string.
118    pub fn to_npub(&self) -> String {
119        const NPUB_HRP: Hrp = Hrp::parse_unchecked("npub");
120        bech32::encode::<Bech32>(NPUB_HRP, &self.public_key)
121            .expect("bech32 encode of 32-byte pubkey with valid HRP is infallible")
122    }
123
124    /// The secret key bytes.
125    pub fn secret_bytes(&self) -> &[u8; 32] {
126        &self.secret_key
127    }
128
129    /// The public key bytes.
130    pub fn public_bytes(&self) -> &[u8; 32] {
131        &self.public_key
132    }
133
134    /// The public key as hex.
135    pub fn public_hex(&self) -> String {
136        hex::encode(self.public_key)
137    }
138
139    /// Sign a message, returning a 64-byte Schnorr signature.
140    pub fn sign(&self, message: &[u8]) -> Result<[u8; 64]> {
141        use k256::schnorr::signature::Signer;
142
143        let signing_key = SigningKey::from_bytes(&*self.secret_key)
144            .map_err(|_| CryptoError::invalid_key("invalid signing key"))?;
145
146        let signature = signing_key.sign(message);
147        Ok(signature.to_bytes())
148    }
149}
150
151impl Clone for NostrKeypair {
152    fn clone(&self) -> Self {
153        let mut secret_copy = *self.secret_key;
154        Self {
155            secret_key: MlockedBox::new(&mut secret_copy),
156            public_key: self.public_key,
157        }
158    }
159}
160
161/// Metadata for a stored key record.
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct KeyRecord {
164    /// Unique identifier derived from public key.
165    pub id: [u8; 32],
166    /// The public key bytes.
167    pub pubkey: [u8; 32],
168    /// Type of key.
169    pub key_type: KeyType,
170    /// Human-readable name.
171    pub name: String,
172    /// Unix timestamp when the key was created.
173    pub created_at: i64,
174    /// Unix timestamp of last use.
175    pub last_used: Option<i64>,
176    /// Number of signatures made with this key.
177    pub sign_count: u64,
178    /// The encrypted secret key bytes.
179    pub encrypted_secret: Vec<u8>,
180}
181
182impl KeyRecord {
183    /// Create a new key record.
184    pub fn new(
185        pubkey: [u8; 32],
186        key_type: KeyType,
187        name: String,
188        encrypted_secret: Vec<u8>,
189    ) -> Self {
190        let id = crypto::blake2b_256(&pubkey);
191        let created_at = chrono::Utc::now().timestamp();
192
193        Self {
194            id,
195            pubkey,
196            key_type,
197            name,
198            created_at,
199            last_used: None,
200            sign_count: 0,
201            encrypted_secret,
202        }
203    }
204
205    /// The npub string, if this is a Nostr key.
206    pub fn npub(&self) -> Option<String> {
207        if self.key_type == KeyType::Nostr {
208            const NPUB_HRP: Hrp = Hrp::parse_unchecked("npub");
209            Some(
210                bech32::encode::<Bech32>(NPUB_HRP, &self.pubkey)
211                    .expect("bech32 encode of 32-byte pubkey with valid HRP is infallible"),
212            )
213        } else {
214            None
215        }
216    }
217}
218
219/// Decode an npub to raw bytes.
220///
221/// # Example
222///
223/// ```
224/// use keep_core::keys::{NostrKeypair, npub_to_bytes};
225///
226/// let keypair = NostrKeypair::generate()?;
227/// let npub = keypair.to_npub();
228/// let bytes = npub_to_bytes(&npub)?;
229/// assert_eq!(&bytes, keypair.public_bytes());
230/// # Ok::<(), keep_core::error::KeepError>(())
231/// ```
232///
233/// # Errors
234///
235/// Returns [`KeepError::InvalidNpub`] if the string is not a valid npub.
236pub fn npub_to_bytes(npub: &str) -> Result<[u8; 32]> {
237    let (hrp, data) = bech32::decode(npub).map_err(|e| {
238        KeepError::InvalidNpub(format!(
239            "not valid bech32 ({e}); expected an npub of the form 'npub1...' (63 chars)"
240        ))
241    })?;
242
243    if hrp.as_str() != "npub" {
244        return Err(KeepError::InvalidNpub(format!(
245            "wrong prefix '{}' (expected 'npub'). Did you paste an nsec or another bech32 entity?",
246            hrp.as_str()
247        )));
248    }
249
250    if data.len() != 32 {
251        return Err(KeepError::InvalidNpub(format!(
252            "decoded payload is {} bytes (expected 32). The npub is bech32-valid but wrong length.",
253            data.len()
254        )));
255    }
256
257    let mut pubkey = [0u8; 32];
258    pubkey.copy_from_slice(&data);
259    Ok(pubkey)
260}
261
262/// Encode raw bytes as an npub.
263///
264/// # Example
265///
266/// ```
267/// use keep_core::keys::{NostrKeypair, bytes_to_npub};
268///
269/// let keypair = NostrKeypair::generate().unwrap();
270/// let npub = bytes_to_npub(keypair.public_bytes());
271/// assert!(npub.starts_with("npub1"));
272/// ```
273pub fn bytes_to_npub(pubkey: &[u8; 32]) -> String {
274    const NPUB_HRP: Hrp = Hrp::parse_unchecked("npub");
275    bech32::encode::<Bech32>(NPUB_HRP, pubkey)
276        .expect("bech32 encode of 32-byte pubkey with valid HRP is infallible")
277}
278
279/// NIP-49 encrypted private key (ncryptsec) support.
280pub mod nip49 {
281    use bech32::{Bech32, Hrp};
282    use chacha20poly1305::aead::{Aead, KeyInit, Payload};
283    use chacha20poly1305::{XChaCha20Poly1305, XNonce};
284    use unicode_normalization::UnicodeNormalization;
285    use zeroize::{Zeroize, Zeroizing};
286
287    use crate::entropy;
288    use crate::error::{CryptoError, KeepError, Result};
289
290    const VERSION: u8 = 0x02;
291    const DEFAULT_LOG_N: u8 = 16;
292    const MAX_LOG_N: u8 = 20;
293
294    /// Encrypt a secret key with a password, returning an ncryptsec string.
295    pub fn encrypt(secret_key: &[u8; 32], password: &str, log_n: Option<u8>) -> Result<String> {
296        if password.is_empty() {
297            return Err(KeepError::InvalidInput(
298                "ncryptsec password must not be empty".into(),
299            ));
300        }
301        let log_n = log_n.unwrap_or(DEFAULT_LOG_N);
302        if log_n > MAX_LOG_N {
303            return Err(KeepError::InvalidInput(format!(
304                "ncryptsec log_n too large: {log_n} (max {MAX_LOG_N})"
305            )));
306        }
307        let password_nfkc = Zeroizing::new(password.nfkc().collect::<String>());
308
309        let salt: [u8; 16] = entropy::try_random_bytes()?;
310        let symmetric_key = derive_key(&password_nfkc, &salt, log_n)?;
311
312        let nonce: [u8; 24] = entropy::try_random_bytes()?;
313        let key_security_byte: u8 = 0x01;
314
315        let cipher = XChaCha20Poly1305::new_from_slice(symmetric_key.as_ref())
316            .map_err(|_| CryptoError::encryption("NIP-49 key init failed"))?;
317        let payload = Payload {
318            msg: secret_key.as_slice(),
319            aad: &[key_security_byte],
320        };
321        let ciphertext = cipher
322            .encrypt(&XNonce::from(nonce), payload)
323            .map_err(|_| CryptoError::encryption("NIP-49 encryption failed"))?;
324
325        let mut concat = Vec::with_capacity(91);
326        concat.push(VERSION);
327        concat.push(log_n);
328        concat.extend_from_slice(&salt);
329        concat.extend_from_slice(&nonce);
330        concat.push(key_security_byte);
331        concat.extend_from_slice(&ciphertext);
332
333        const NCRYPTSEC_HRP: Hrp = Hrp::parse_unchecked("ncryptsec");
334        bech32::encode::<Bech32>(NCRYPTSEC_HRP, &concat)
335            .map_err(|_| CryptoError::encryption("bech32 encoding failed").into())
336    }
337
338    /// Decrypt an ncryptsec string with a password, returning the secret key.
339    pub fn decrypt(ncryptsec: &str, password: &str) -> Result<Zeroizing<[u8; 32]>> {
340        let (hrp, mut data) = bech32::decode(ncryptsec)
341            .map_err(|_| KeepError::InvalidInput("invalid bech32".into()))?;
342
343        if hrp.as_str() != "ncryptsec" {
344            data.zeroize();
345            return Err(KeepError::InvalidInput("not an ncryptsec string".into()));
346        }
347
348        if data.len() != 91 {
349            data.zeroize();
350            return Err(KeepError::InvalidInput(format!(
351                "invalid ncryptsec length: expected 91, got {}",
352                data.len()
353            )));
354        }
355
356        let version = data[0];
357        if version != VERSION {
358            data.zeroize();
359            return Err(KeepError::InvalidInput(format!(
360                "unsupported ncryptsec version: {version}"
361            )));
362        }
363
364        let log_n = data[1];
365        if log_n > MAX_LOG_N {
366            data.zeroize();
367            return Err(KeepError::InvalidInput(format!(
368                "ncryptsec log_n too large: {log_n} (max {MAX_LOG_N})"
369            )));
370        }
371        let salt: [u8; 16] = data[2..18].try_into().expect("length checked");
372        let nonce: [u8; 24] = data[18..42].try_into().expect("length checked");
373        let key_security_byte = data[42];
374        let ciphertext = data[43..].to_vec();
375        data.zeroize();
376
377        let password_nfkc = Zeroizing::new(password.nfkc().collect::<String>());
378        let symmetric_key = derive_key(&password_nfkc, &salt, log_n)?;
379
380        let cipher = XChaCha20Poly1305::new_from_slice(symmetric_key.as_ref())
381            .map_err(|_| KeepError::DecryptionFailed)?;
382        let payload = Payload {
383            msg: &ciphertext,
384            aad: &[key_security_byte],
385        };
386        let mut plaintext = cipher
387            .decrypt(&XNonce::from(nonce), payload)
388            .map_err(|_| KeepError::DecryptionFailed)?;
389
390        if plaintext.len() != 32 {
391            plaintext.zeroize();
392            return Err(CryptoError::decryption("invalid decrypted key length").into());
393        }
394
395        let mut key = Zeroizing::new([0u8; 32]);
396        key.copy_from_slice(&plaintext);
397        plaintext.zeroize();
398        Ok(key)
399    }
400
401    fn derive_key(password: &str, salt: &[u8; 16], log_n: u8) -> Result<Zeroizing<[u8; 32]>> {
402        let params = scrypt::Params::new(log_n, 8, 1)
403            .map_err(|e| CryptoError::kdf(format!("scrypt params: {e}")))?;
404
405        let mut key = Zeroizing::new([0u8; 32]);
406        scrypt::scrypt(password.as_bytes(), salt, &params, &mut *key)
407            .map_err(|e| CryptoError::kdf(format!("scrypt: {e}")))?;
408
409        Ok(key)
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    #[test]
418    fn test_keypair_generation() {
419        let kp = NostrKeypair::generate().unwrap();
420
421        let nsec = kp.to_nsec();
422        let npub = kp.to_npub();
423
424        assert!(nsec.starts_with("nsec1"));
425        assert!(npub.starts_with("npub1"));
426    }
427
428    #[test]
429    fn test_nsec_roundtrip() {
430        let kp = NostrKeypair::generate().unwrap();
431        let nsec = kp.to_nsec();
432
433        let kp2 = NostrKeypair::from_nsec(&nsec).unwrap();
434
435        assert_eq!(kp.secret_bytes(), kp2.secret_bytes());
436        assert_eq!(kp.public_bytes(), kp2.public_bytes());
437    }
438
439    #[test]
440    fn test_sign_verify() {
441        let kp = NostrKeypair::generate().unwrap();
442        let message = b"test message";
443
444        let sig = kp.sign(message).unwrap();
445        assert_eq!(sig.len(), 64);
446    }
447
448    #[test]
449    fn test_invalid_nsec() {
450        let result = NostrKeypair::from_nsec("invalid");
451        assert!(result.is_err());
452
453        let result = NostrKeypair::from_nsec("npub1abc");
454        assert!(result.is_err());
455    }
456
457    #[test]
458    fn test_nip49_roundtrip() {
459        let kp = NostrKeypair::generate().unwrap();
460        let password = "test-password-123";
461
462        let ncryptsec = nip49::encrypt(kp.secret_bytes(), password, Some(16)).unwrap();
463        assert!(ncryptsec.starts_with("ncryptsec1"));
464
465        let decrypted = nip49::decrypt(&ncryptsec, password).unwrap();
466        assert_eq!(&*decrypted, kp.secret_bytes());
467    }
468
469    #[test]
470    fn test_nip49_wrong_password() {
471        let kp = NostrKeypair::generate().unwrap();
472        let ncryptsec = nip49::encrypt(kp.secret_bytes(), "correct", Some(16)).unwrap();
473        let result = nip49::decrypt(&ncryptsec, "wrong");
474        assert!(result.is_err());
475    }
476
477    #[test]
478    fn test_nip49_spec_vector() {
479        let ncryptsec = "ncryptsec1qgg9947rlpvqu76pj5ecreduf9jxhselq2nae2kghhvd5g7dgjtcxfqtd67p9m0w57lspw8gsq6yphnm8623nsl8xn9j4jdzz84zm3frztj3z7s35vpzmqf6ksu8r89qk5z2zxfmu5gv8th8wclt0h4p";
480        let expected_hex = "3501454135014541350145413501453fefb02227e449e57cf4d3a3ce05378683";
481        let expected: Vec<u8> = hex::decode(expected_hex).unwrap();
482
483        let decrypted = nip49::decrypt(ncryptsec, "nostr").unwrap();
484        assert_eq!(decrypted.as_slice(), expected.as_slice());
485    }
486}