chie-crypto 0.2.0

Cryptographic primitives for CHIE Protocol
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! OpenSSH Key Format Support
//!
//! This module provides functionality to import and export Ed25519 keys in OpenSSH formats.
//! Supports both public key format (ssh-ed25519) and private key format (OpenSSH private key).
//!
//! # Examples
//!
//! ```
//! use chie_crypto::openssh::{SshPublicKey, SshPrivateKey};
//! use chie_crypto::signing::KeyPair;
//!
//! // Generate a keypair
//! let keypair = KeyPair::generate();
//!
//! // Export as SSH public key
//! let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key());
//! let ssh_pub_str = ssh_pub.to_string_with_comment("user@host");
//!
//! // Parse SSH public key
//! let parsed = SshPublicKey::parse(&ssh_pub_str).unwrap();
//! assert_eq!(parsed.key_data, ssh_pub.key_data);
//!
//! // Export as SSH private key
//! let ssh_priv = SshPrivateKey::from_ed25519(&keypair);
//! let pem = ssh_priv.to_pem();
//! ```

use crate::signing::{KeyPair, PublicKey};
use base64::{Engine, engine::general_purpose::STANDARD};
use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

/// SSH key format errors
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum SshKeyError {
    /// Invalid SSH key format
    #[error("Invalid SSH key format: {0}")]
    InvalidFormat(String),

    /// Invalid key length
    #[error("Invalid key length: expected {expected}, got {actual}")]
    InvalidLength { expected: usize, actual: usize },

    /// Unsupported algorithm
    #[error("Unsupported algorithm: {0}")]
    UnsupportedAlgorithm(String),

    /// Base64 decode error
    #[error("Base64 decode error: {0}")]
    Base64Error(String),

    /// Unexpected end of data
    #[error("Unexpected end of data")]
    UnexpectedEof,

    /// UTF-8 decode error
    #[error("UTF-8 decode error: {0}")]
    Utf8Error(String),

    /// Invalid secret key
    #[error("Invalid secret key")]
    InvalidSecretKey,
}

/// Result type for SSH key operations
pub type SshKeyResult<T> = Result<T, SshKeyError>;

const SSH_ED25519_KEY_TYPE: &str = "ssh-ed25519";
const OPENSSH_PRIVATE_KEY_HEADER: &str = "-----BEGIN OPENSSH PRIVATE KEY-----";
const OPENSSH_PRIVATE_KEY_FOOTER: &str = "-----END OPENSSH PRIVATE KEY-----";
const OPENSSH_AUTH_MAGIC: &[u8] = b"openssh-key-v1\0";

/// SSH public key in OpenSSH format
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SshPublicKey {
    /// Algorithm identifier (e.g., "ssh-ed25519")
    pub algorithm: String,
    /// Raw key data (32 bytes for Ed25519)
    pub key_data: Vec<u8>,
    /// Optional comment
    pub comment: Option<String>,
}

impl SshPublicKey {
    /// Create SSH public key from Ed25519 public key
    pub fn from_ed25519(public_key: &PublicKey) -> Self {
        Self {
            algorithm: SSH_ED25519_KEY_TYPE.to_string(),
            key_data: public_key.to_vec(),
            comment: None,
        }
    }

    /// Set comment for the SSH key
    pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Convert to OpenSSH public key format
    ///
    /// Format: `ssh-ed25519 <base64-encoded-key> [optional-comment]`
    pub fn to_openssh_format(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // Write algorithm length and data
        write_string(&mut buf, &self.algorithm);

        // Write key data length and data
        write_bytes(&mut buf, &self.key_data);

        buf
    }

    /// Encode as OpenSSH public key string
    pub fn to_string_with_comment(&self, comment: &str) -> String {
        let encoded = STANDARD.encode(self.to_openssh_format());
        format!("{} {} {}", self.algorithm, encoded, comment)
    }

    /// Encode as OpenSSH public key string without comment
    pub fn to_string_no_comment(&self) -> String {
        let encoded = STANDARD.encode(self.to_openssh_format());
        format!("{} {}", self.algorithm, encoded)
    }

    /// Parse OpenSSH public key from string
    ///
    /// Format: `ssh-ed25519 <base64-encoded-key> [optional-comment]`
    pub fn parse(s: &str) -> SshKeyResult<Self> {
        let parts: Vec<&str> = s.split_whitespace().collect();

        if parts.len() < 2 {
            return Err(SshKeyError::InvalidFormat(
                "Invalid SSH public key format".to_string(),
            ));
        }

        let algorithm = parts[0].to_string();
        let encoded = parts[1];
        let comment = if parts.len() > 2 {
            Some(parts[2..].join(" "))
        } else {
            None
        };

        // Decode base64
        let data = STANDARD
            .decode(encoded)
            .map_err(|e| SshKeyError::Base64Error(e.to_string()))?;

        // Parse the binary format
        let mut offset = 0;
        let parsed_algo = read_string(&data, &mut offset)?;

        if parsed_algo != algorithm {
            return Err(SshKeyError::InvalidFormat(format!(
                "Algorithm mismatch: {} vs {}",
                parsed_algo, algorithm
            )));
        }

        let key_data = read_bytes(&data, &mut offset)?;

        if algorithm == SSH_ED25519_KEY_TYPE && key_data.len() != 32 {
            return Err(SshKeyError::InvalidLength {
                expected: 32,
                actual: key_data.len(),
            });
        }

        Ok(Self {
            algorithm,
            key_data,
            comment,
        })
    }

    /// Convert to Ed25519 public key
    pub fn to_ed25519(&self) -> SshKeyResult<PublicKey> {
        if self.algorithm != SSH_ED25519_KEY_TYPE {
            return Err(SshKeyError::UnsupportedAlgorithm(self.algorithm.clone()));
        }

        if self.key_data.len() != 32 {
            return Err(SshKeyError::InvalidLength {
                expected: 32,
                actual: self.key_data.len(),
            });
        }

        let mut bytes = [0u8; 32];
        bytes.copy_from_slice(&self.key_data);
        Ok(bytes)
    }
}

impl fmt::Display for SshPublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(comment) = &self.comment {
            write!(f, "{}", self.to_string_with_comment(comment))
        } else {
            write!(f, "{}", self.to_string_no_comment())
        }
    }
}

/// SSH private key in OpenSSH format
#[derive(Clone, Serialize, Deserialize)]
pub struct SshPrivateKey {
    /// Public key data
    pub public_key: Vec<u8>,
    /// Private key data (64 bytes for Ed25519: 32 bytes seed + 32 bytes public)
    pub private_key: Vec<u8>,
    /// Optional comment
    pub comment: Option<String>,
}

impl SshPrivateKey {
    /// Create SSH private key from Ed25519 keypair
    pub fn from_ed25519(keypair: &KeyPair) -> Self {
        // OpenSSH format stores 64 bytes: 32-byte seed + 32-byte public key
        let secret = keypair.secret_key();
        let public = keypair.public_key();
        let mut private_key = Vec::with_capacity(64);
        private_key.extend_from_slice(&secret);
        private_key.extend_from_slice(&public);

        Self {
            public_key: public.to_vec(),
            private_key,
            comment: None,
        }
    }

    /// Set comment for the SSH key
    pub fn with_comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Convert to OpenSSH private key format (binary)
    pub fn to_openssh_format(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // Magic header
        buf.extend_from_slice(OPENSSH_AUTH_MAGIC);

        // Cipher name (none - unencrypted)
        write_string(&mut buf, "none");

        // KDF name (none)
        write_string(&mut buf, "none");

        // KDF options (empty)
        write_string(&mut buf, "");

        // Number of keys (1)
        buf.extend_from_slice(&1u32.to_be_bytes());

        // Public key section
        let mut public_section = Vec::new();
        write_string(&mut public_section, SSH_ED25519_KEY_TYPE);
        write_bytes(&mut public_section, &self.public_key);
        write_bytes(&mut buf, &public_section);

        // Private key section
        let mut private_section = Vec::new();

        // Check integers (for encryption detection, both should be same)
        let check = rand::random::<u32>();
        private_section.extend_from_slice(&check.to_be_bytes());
        private_section.extend_from_slice(&check.to_be_bytes());

        // Algorithm
        write_string(&mut private_section, SSH_ED25519_KEY_TYPE);

        // Public key
        write_bytes(&mut private_section, &self.public_key);

        // Private key (Ed25519: 64 bytes)
        write_bytes(&mut private_section, &self.private_key);

        // Comment
        write_string(&mut private_section, self.comment.as_deref().unwrap_or(""));

        // Padding to block size (8 bytes)
        let padding_len = 8 - (private_section.len() % 8);
        for i in 1..=padding_len {
            private_section.push(i as u8);
        }

        write_bytes(&mut buf, &private_section);

        buf
    }

    /// Encode as PEM format
    pub fn to_pem(&self) -> String {
        let data = self.to_openssh_format();
        let encoded = STANDARD.encode(&data);

        // Split into 70-character lines
        let mut result = String::new();
        result.push_str(OPENSSH_PRIVATE_KEY_HEADER);
        result.push('\n');

        for chunk in encoded.as_bytes().chunks(70) {
            result.push_str(std::str::from_utf8(chunk).unwrap());
            result.push('\n');
        }

        result.push_str(OPENSSH_PRIVATE_KEY_FOOTER);
        result.push('\n');

        result
    }

    /// Parse OpenSSH private key from PEM format
    pub fn from_pem(pem: &str) -> SshKeyResult<Self> {
        // Remove headers and whitespace
        let pem = pem
            .lines()
            .filter(|line| {
                !line.contains("BEGIN OPENSSH PRIVATE KEY")
                    && !line.contains("END OPENSSH PRIVATE KEY")
            })
            .collect::<String>();

        let data = STANDARD
            .decode(pem.trim())
            .map_err(|e| SshKeyError::Base64Error(e.to_string()))?;

        Self::parse_binary(&data)
    }

    /// Parse binary OpenSSH private key format
    pub fn parse_binary(data: &[u8]) -> SshKeyResult<Self> {
        let mut offset = 0;

        // Check magic
        if data.len() < OPENSSH_AUTH_MAGIC.len()
            || &data[..OPENSSH_AUTH_MAGIC.len()] != OPENSSH_AUTH_MAGIC
        {
            return Err(SshKeyError::InvalidFormat(
                "Invalid OpenSSH private key magic".to_string(),
            ));
        }
        offset += OPENSSH_AUTH_MAGIC.len();

        // Read cipher (should be "none" for unencrypted)
        let cipher = read_string(data, &mut offset)?;
        if cipher != "none" {
            return Err(SshKeyError::InvalidFormat(
                "Encrypted SSH keys not supported yet".to_string(),
            ));
        }

        // Read KDF (should be "none")
        let _kdf = read_string(data, &mut offset)?;

        // Read KDF options (should be empty)
        let _kdf_options = read_bytes(data, &mut offset)?;

        // Read number of keys
        let num_keys = read_u32(data, &mut offset)?;
        if num_keys != 1 {
            return Err(SshKeyError::InvalidFormat(format!(
                "Expected 1 key, found {}",
                num_keys
            )));
        }

        // Read public key section
        let _public_section = read_bytes(data, &mut offset)?;

        // Read private key section
        let private_section = read_bytes(data, &mut offset)?;
        let mut priv_offset = 0;

        // Check integers
        let check1 = read_u32(&private_section, &mut priv_offset)?;
        let check2 = read_u32(&private_section, &mut priv_offset)?;
        if check1 != check2 {
            return Err(SshKeyError::InvalidFormat(
                "Checksum mismatch (possibly encrypted)".to_string(),
            ));
        }

        // Read algorithm
        let algorithm = read_string(&private_section, &mut priv_offset)?;
        if algorithm != SSH_ED25519_KEY_TYPE {
            return Err(SshKeyError::UnsupportedAlgorithm(algorithm));
        }

        // Read public key
        let public_key = read_bytes(&private_section, &mut priv_offset)?;

        // Read private key
        let private_key = read_bytes(&private_section, &mut priv_offset)?;

        // Read comment
        let comment = read_string(&private_section, &mut priv_offset)?;
        let comment = if comment.is_empty() {
            None
        } else {
            Some(comment)
        };

        Ok(Self {
            public_key,
            private_key,
            comment,
        })
    }

    /// Convert to Ed25519 keypair
    pub fn to_ed25519(&self) -> SshKeyResult<KeyPair> {
        if self.private_key.len() != 64 {
            return Err(SshKeyError::InvalidLength {
                expected: 64,
                actual: self.private_key.len(),
            });
        }

        // Extract the first 32 bytes (the seed/secret key)
        let mut secret = [0u8; 32];
        secret.copy_from_slice(&self.private_key[..32]);

        KeyPair::from_secret_key(&secret).map_err(|_| SshKeyError::InvalidSecretKey)
    }
}

// Helper functions for SSH binary format

fn write_string(buf: &mut Vec<u8>, s: &str) {
    let bytes = s.as_bytes();
    buf.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
    buf.extend_from_slice(bytes);
}

fn write_bytes(buf: &mut Vec<u8>, data: &[u8]) {
    buf.extend_from_slice(&(data.len() as u32).to_be_bytes());
    buf.extend_from_slice(data);
}

fn read_u32(data: &[u8], offset: &mut usize) -> SshKeyResult<u32> {
    if *offset + 4 > data.len() {
        return Err(SshKeyError::UnexpectedEof);
    }

    let mut bytes = [0u8; 4];
    bytes.copy_from_slice(&data[*offset..*offset + 4]);
    *offset += 4;

    Ok(u32::from_be_bytes(bytes))
}

fn read_string(data: &[u8], offset: &mut usize) -> SshKeyResult<String> {
    let bytes = read_bytes(data, offset)?;
    String::from_utf8(bytes).map_err(|e| SshKeyError::Utf8Error(e.to_string()))
}

fn read_bytes(data: &[u8], offset: &mut usize) -> SshKeyResult<Vec<u8>> {
    let len = read_u32(data, offset)? as usize;

    if *offset + len > data.len() {
        return Err(SshKeyError::UnexpectedEof);
    }

    let bytes = data[*offset..*offset + len].to_vec();
    *offset += len;

    Ok(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ssh_public_key_roundtrip() {
        let keypair = KeyPair::generate();
        let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key());

        let formatted = ssh_pub.to_string_with_comment("test@host");
        let parsed = SshPublicKey::parse(&formatted).unwrap();

        assert_eq!(parsed.algorithm, SSH_ED25519_KEY_TYPE);
        assert_eq!(parsed.key_data, ssh_pub.key_data);
        assert_eq!(parsed.comment, Some("test@host".to_string()));
    }

    #[test]
    fn test_ssh_public_key_no_comment() {
        let keypair = KeyPair::generate();
        let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key());

        let formatted = ssh_pub.to_string_no_comment();
        let parsed = SshPublicKey::parse(&formatted).unwrap();

        assert_eq!(parsed.key_data, ssh_pub.key_data);
        assert_eq!(parsed.comment, None);
    }

    #[test]
    fn test_ssh_public_key_to_ed25519() {
        let keypair = KeyPair::generate();
        let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key());

        let ed25519_pub = ssh_pub.to_ed25519().unwrap();
        assert_eq!(&ed25519_pub, &keypair.public_key());
    }

    #[test]
    fn test_ssh_private_key_pem_roundtrip() {
        let keypair = KeyPair::generate();
        let ssh_priv = SshPrivateKey::from_ed25519(&keypair).with_comment("test@host");

        let pem = ssh_priv.to_pem();
        assert!(pem.contains(OPENSSH_PRIVATE_KEY_HEADER));
        assert!(pem.contains(OPENSSH_PRIVATE_KEY_FOOTER));

        let parsed = SshPrivateKey::from_pem(&pem).unwrap();
        assert_eq!(parsed.public_key, ssh_priv.public_key);
        assert_eq!(parsed.private_key, ssh_priv.private_key);
        assert_eq!(parsed.comment, ssh_priv.comment);
    }

    #[test]
    fn test_ssh_private_key_to_ed25519() {
        let keypair = KeyPair::generate();
        let ssh_priv = SshPrivateKey::from_ed25519(&keypair);

        let recovered = ssh_priv.to_ed25519().unwrap();
        assert_eq!(&recovered.public_key(), &keypair.public_key());
        assert_eq!(recovered.secret_key(), keypair.secret_key());
    }

    #[test]
    fn test_ssh_keys_compatibility() {
        let keypair = KeyPair::generate();

        // Export both public and private
        let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key());
        let ssh_priv = SshPrivateKey::from_ed25519(&keypair);

        // Ensure public keys match
        assert_eq!(ssh_pub.key_data, ssh_priv.public_key);

        // Recover keypair from private key
        let recovered = ssh_priv.to_ed25519().unwrap();
        assert_eq!(&recovered.public_key(), &keypair.public_key());
    }

    #[test]
    fn test_invalid_ssh_public_key() {
        assert!(SshPublicKey::parse("invalid").is_err());
        assert!(SshPublicKey::parse("ssh-ed25519").is_err());
        assert!(SshPublicKey::parse("ssh-ed25519 !!!invalid-base64!!!").is_err());
    }

    #[test]
    fn test_ssh_public_key_with_multiword_comment() {
        let keypair = KeyPair::generate();
        let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key());

        let formatted = ssh_pub.to_string_with_comment("user@host with spaces");
        let parsed = SshPublicKey::parse(&formatted).unwrap();

        assert_eq!(parsed.comment, Some("user@host with spaces".to_string()));
    }

    #[test]
    fn test_openssh_format_structure() {
        let keypair = KeyPair::generate();
        let ssh_priv = SshPrivateKey::from_ed25519(&keypair);

        let binary = ssh_priv.to_openssh_format();

        // Check magic
        assert_eq!(&binary[..OPENSSH_AUTH_MAGIC.len()], OPENSSH_AUTH_MAGIC);
    }

    #[test]
    fn test_write_read_string() {
        let mut buf = Vec::new();
        write_string(&mut buf, "test");

        let mut offset = 0;
        let s = read_string(&buf, &mut offset).unwrap();
        assert_eq!(s, "test");
        assert_eq!(offset, buf.len());
    }

    #[test]
    fn test_write_read_bytes() {
        let mut buf = Vec::new();
        let data = vec![1, 2, 3, 4, 5];
        write_bytes(&mut buf, &data);

        let mut offset = 0;
        let read = read_bytes(&buf, &mut offset).unwrap();
        assert_eq!(read, data);
        assert_eq!(offset, buf.len());
    }

    #[test]
    fn test_pem_line_wrapping() {
        let keypair = KeyPair::generate();
        let ssh_priv = SshPrivateKey::from_ed25519(&keypair);
        let pem = ssh_priv.to_pem();

        // Check that lines are wrapped (no line should be > 71 chars including newline)
        for line in pem.lines() {
            if !line.contains("BEGIN") && !line.contains("END") {
                assert!(line.len() <= 70, "Line too long: {}", line.len());
            }
        }
    }

    #[test]
    fn test_serialization() {
        let keypair = KeyPair::generate();
        let ssh_pub = SshPublicKey::from_ed25519(&keypair.public_key()).with_comment("test@host");

        let serialized = crate::codec::encode(&ssh_pub).unwrap();
        let deserialized: SshPublicKey = crate::codec::decode(&serialized).unwrap();

        assert_eq!(deserialized.algorithm, ssh_pub.algorithm);
        assert_eq!(deserialized.key_data, ssh_pub.key_data);
        assert_eq!(deserialized.comment, ssh_pub.comment);
    }
}