age-setup 0.1.0

a rust library that creates X25519 key pairs and uses age as its foundation and is very easy to use
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
```
.  # ./src
├── apis
│   ├── build.rs
│   ├── mod.rs
├── build
│   ├── identity.rs
│   ├── mod.rs
│   ├── recipient.rs
├── errors
│   ├── buildings.rs
│   ├── mod.rs
│   ├── security.rs
│   ├── validation.rs
├── lib.rs
├── security
│   ├── mod.rs
│   ├── zeroize.rs
├── types
│   ├── keypair.rs
│   ├── mod.rs
│   ├── public_key.rs
│   ├── secret_key.rs
│   ├── validation.rs
```
## ./src/lib.rs

```rust
//! # age-setup
//!
//! A library for generating age keypairs (X25519) with validation and secure memory handling.
//!
//! This crate provides a simple way to create a keypair for age encryption,
//! returning a [`KeyPair`] containing a public key (starting with "age1") and a secret key.
//! The secret key is automatically zeroized on drop for security.
//!
//! # Example
//!
//! ```
//! use age_setup::build_keypair;
//!
//! let keypair = build_keypair().expect("failed to generate keypair");
//! println!("Public key: {}", keypair.public);
//! println!("Secret key: [REDACTED]"); // Display redacts secret
//! // Access raw secret with .expose() – use with caution!
//! # let _ = keypair.secret.expose();
//! ```
//!
//! # Features
//! - Generate X25519 keypairs compatible with age.
//! - Public key validation (must start with "age1").
//! - Secret key zeroization on drop.
//! - Redacted `Display` for secret key.
//! - Error handling with detailed error types.

pub mod apis;
pub mod build;
pub mod errors;
pub mod security;
pub mod types;

pub use apis::build::build_keypair;
pub use errors::{Error, Result};
pub use types::KeyPair;
```
## ./src/types/mod.rs

```rust
pub mod keypair;
pub mod public_key;
pub mod secret_key;
pub mod validation;
pub use keypair::KeyPair;
pub use public_key::PublicKey;
pub use secret_key::SecretKey;
```
## ./src/types/keypair.rs

```rust
//! Keypair structure combining public and secret keys.

use crate::types::{PublicKey, SecretKey};

/// A keypair consisting of an age public key and its corresponding secret key.
///
/// This is the main output of [`build_keypair`](crate::build_keypair).
/// Both fields are public for direct access.
#[derive(Debug)]
pub struct KeyPair {
    /// The public key (starts with "age1").
    pub public: PublicKey,
    /// The secret key (zeroized on drop).
    pub secret: SecretKey,
}

impl KeyPair {
    /// Creates a new keypair (internal use only).
    pub(crate) fn new(public: PublicKey, secret: SecretKey) -> Self {
        Self { public, secret }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{PublicKey, SecretKey};

    #[test]
    fn test_keypair_new() {
        let pub_key = PublicKey::new("age1pub".to_string()).unwrap();
        let secret_key = SecretKey::new("secret".to_string());
        let kp = KeyPair::new(pub_key, secret_key);
        assert_eq!(kp.public.expose(), "age1pub");
        assert_eq!(kp.secret.expose(), "secret");
    }
}
```
## ./src/types/public_key.rs

```rust
//! Public key type with validation and display.

use crate::errors::Result;
use crate::types::validation::validate_age_prefix;
use std::fmt;

/// An age public key, guaranteed to start with "age1".
///
/// Constructed via `PublicKey::new`, which validates the format.
/// Can be displayed or converted to a string using `expose()`.
#[derive(Debug, Clone)]
pub struct PublicKey(String);

impl PublicKey {
    /// Creates a new public key after validating the prefix.
    ///
    /// # Errors
    /// Returns `ValidationError` if the string is empty or doesn't start with "age1".
    pub(crate) fn new(raw: String) -> Result<Self> {
        validate_age_prefix(&raw)?;
        Ok(Self(raw))
    }

    /// Returns the raw string representation of the public key.
    ///
    /// # Example
    /// ```
    /// # use age_setup::types::PublicKey;
    /// # let pk = PublicKey::new("age1example".to_string()).unwrap();
    /// assert_eq!(pk.expose(), "age1example");
    /// ```
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl AsRef<str> for PublicKey {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

    #[test]
    fn test_public_key_new_valid() {
        let pk = PublicKey::new("age1valid".to_string());
        assert!(pk.is_ok());
        assert_eq!(pk.unwrap().expose(), "age1valid");
    }

    #[test]
    fn test_public_key_new_invalid() {
        let pk = PublicKey::new("invalid".to_string());
        assert!(pk.is_err());
    }

    #[test]
    fn test_public_key_display() {
        let pk = PublicKey::new("age1test".to_string()).unwrap();
        assert_eq!(format!("{}", pk), "age1test");
    }

    #[test]
    fn test_public_key_asref() {
        let pk = PublicKey::new("age1asref".to_string()).unwrap();
        let s: &str = pk.as_ref();
        assert_eq!(s, "age1asref");
    }

    #[test]
    fn test_public_key_clone() {
        let pk1 = PublicKey::new("age1clone".to_string()).unwrap();
        let pk2 = pk1.clone();
        assert_eq!(pk1.expose(), pk2.expose());
    }
}
```
## ./src/types/secret_key.rs

```rust
//! Secret key type with automatic zeroization on drop.

use crate::security::zeroize::wipe_memory;
use std::fmt;

/// An age secret key that securely wipes its memory when dropped.
///
/// The secret key is stored as bytes. The `Display` implementation redacts the value,
/// showing `[REDACTED]`. Use `expose()` to get the raw string (use with caution).
#[derive(Debug, Clone)]
pub struct SecretKey {
    inner: Vec<u8>,
}

impl SecretKey {
    /// Creates a new secret key from a string (internal).
    pub(crate) fn new(raw: String) -> Self {
        Self {
            inner: raw.into_bytes(),
        }
    }

    /// Exposes the raw secret key as a string.
    ///
    /// # Panics
    /// Panics if the inner bytes are not valid UTF-8 (should never happen because
    /// the key is created from a valid UTF-8 string).
    ///
    /// # Security
    /// Only use this when absolutely necessary, as it exposes the secret.
    #[must_use]
    pub fn expose(&self) -> &str {
        std::str::from_utf8(&self.inner).expect("SecretKey inner buffer must be valid UTF-8")
    }
}

impl Drop for SecretKey {
    fn drop(&mut self) {
        let _ = wipe_memory(&mut self.inner);
    }
}

impl fmt::Display for SecretKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[REDACTED]")
    }
}

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

    #[test]
    fn test_secret_key_expose() {
        let sk = SecretKey::new("test".to_string());
        assert_eq!(sk.expose(), "test");
    }

    #[test]
    fn test_secret_key_display() {
        let sk = SecretKey::new("test".to_string());
        assert_eq!(format!("{}", sk), "[REDACTED]");
    }

    #[test]
    fn test_secret_key_clone() {
        let sk1 = SecretKey::new("secret".to_string());
        let sk2 = sk1.clone();
        assert_eq!(sk1.expose(), sk2.expose());
    }

    #[test]
    fn test_secret_key_drop_calls_wipe() {
        let sk = SecretKey::new("secret".to_string());
        drop(sk); // Tidak panic, wipe_memory dipanggil
    }
}
```
## ./src/types/validation.rs

```rust
use crate::errors::{Error, Result, ValidationError};
pub(crate) fn validate_age_prefix(key: &str) -> Result<()> {
    if key.is_empty() {
        return Err(Error::from(ValidationError::invalid_public_key(
            "Key is empty",
        )));
    }
    if !key.starts_with("age1") {
        return Err(Error::from(ValidationError::invalid_public_key(format!(
            "Key must start with 'age1', got: {}",
            &key[..key.len().min(10)]
        ))));
    }
    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::Error;

    #[test]
    fn test_validate_age_prefix_empty() {
        let result = validate_age_prefix("");
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Validation(e) => {
                let msg = format!("{}", e);
                assert!(msg.contains("Key is empty"));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn test_validate_age_prefix_wrong_prefix() {
        let result = validate_age_prefix("xyz123");
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Validation(e) => {
                let msg = format!("{}", e);
                assert!(msg.contains("must start with 'age1'"));
                assert!(msg.contains("xyz123"));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn test_validate_age_prefix_short_prefix() {
        let result = validate_age_prefix("age");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_age_prefix_valid() {
        let result = validate_age_prefix("age1abcdef");
        assert!(result.is_ok());
    }
}
```
## ./src/apis/mod.rs

```rust
pub mod build;
```
## ./src/apis/build.rs

```rust
//! Keypair building API.

use crate::build::identity::create_identity;
use crate::build::recipient::extract_recipient;
use crate::errors::Result;
use crate::types::{KeyPair, PublicKey, SecretKey};
use age::secrecy::ExposeSecret;

/// Generates a new age X25519 keypair.
///
/// This function creates a random identity using `age::x25519::Identity::generate()`,
/// extracts the corresponding recipient (public key), and wraps them into a [`KeyPair`].
/// The public key is validated to start with "age1".
///
/// # Returns
/// Returns a [`Result`] containing a [`KeyPair`] on success, or an [`crate::Error`] if validation fails.
///
/// # Example
/// ```
/// # use age_setup::build_keypair;
/// let kp = build_keypair().unwrap();
/// assert!(kp.public.expose().starts_with("age1"));
/// ```
pub fn build_keypair() -> Result<KeyPair> {
    let identity = create_identity()?;
    let recipient = extract_recipient(&identity);
    let public_raw = recipient.to_string();
    let secret_raw = identity.to_string().expose_secret().to_string();
    let public = PublicKey::new(public_raw)?;
    let secret = SecretKey::new(secret_raw);
    Ok(KeyPair::new(public, secret))
}
```
## ./src/errors/mod.rs

```rust
//! Error handling types.

pub mod buildings;
pub mod security;
pub mod validation;

pub use buildings::GenerationError;
pub use security::SecurityError;
pub use validation::ValidationError;

/// Main error type for the crate.
///
/// Encompasses all possible errors during key generation, validation, or security operations.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Error during key generation (e.g., internal library failure).
    #[error("Key generation failed: {0}")]
    Generation(#[from] GenerationError),
    /// Error validating public key format.
    #[error("Validation failed: {0}")]
    Validation(#[from] ValidationError),
    /// Error during security operations (e.g., memory wipe).
    #[error("Security operation failed: {0}")]
    Security(#[from] SecurityError),
}

/// Result type alias using `Error` from this crate.
pub type Result<T> = std::result::Result<T, Error>;

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

    #[test]
    fn test_error_from_generation() {
        let gen_err = GenerationError::IdentityCreationFailed;
        let err: Error = gen_err.into();
        assert!(matches!(err, Error::Generation(_)));
    }

    #[test]
    fn test_error_from_validation() {
        let val_err = ValidationError::invalid_public_key("test");
        let err: Error = val_err.into();
        assert!(matches!(err, Error::Validation(_)));
    }

    #[test]
    fn test_error_from_security() {
        let sec_err = SecurityError::MemoryWipeFailed;
        let err: Error = sec_err.into();
        assert!(matches!(err, Error::Security(_)));
    }

    #[test]
    fn test_error_display() {
        let err = Error::Generation(GenerationError::IdentityCreationFailed);
        assert_eq!(
            format!("{}", err),
            "Key generation failed: Age identity generation failed: internal library error"
        );
    }
}
```
## ./src/errors/validation.rs

```rust
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
    #[error("Invalid public key format: {reason}")]
    InvalidPublicKeyFormat { reason: String },
}
impl ValidationError {
    pub(crate) fn invalid_public_key(reason: impl Into<String>) -> Self {
        Self::InvalidPublicKeyFormat {
            reason: reason.into(),
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validation_error_display() {
        let err = ValidationError::invalid_public_key("test reason");
        let msg = format!("{}", err);
        assert_eq!(msg, "Invalid public key format: test reason");
    }
}
```
## ./src/errors/security.rs

```rust
//! Security operation error types.

/// Errors that occur during security operations (e.g., memory wiping).
#[derive(Debug, thiserror::Error)]
pub enum SecurityError {
    /// Memory wipe operation failed (unlikely, but included for completeness).
    #[error("Memory wipe operation failed")]
    MemoryWipeFailed,
}
```
## ./src/errors/buildings.rs

```rust
//! Key generation error types.

/// Errors that occur during identity generation.
#[derive(Debug, thiserror::Error)]
pub enum GenerationError {
    /// Failed to generate an age identity (internal library issue).
    #[error("Age identity generation failed: internal library error")]
    IdentityCreationFailed,
}
```
## ./src/security/mod.rs

```rust
pub mod zeroize;
```
## ./src/security/zeroize.rs

```rust
//! Memory zeroization utilities.

use crate::errors::Result;
use zeroize::Zeroize;

/// Securely overwrites a byte slice with zeros.
///
/// This function uses the `zeroize` crate to prevent compiler optimizations.
/// It always returns `Ok(())`; the `Result` is kept for future extensibility.
#[must_use = "wipe_memory should be called to ensure memory is cleared"]
pub(crate) fn wipe_memory(data: &mut [u8]) -> Result<()> {
    data.zeroize();
    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_wipe_memory_zeroizes() {
        let mut data = vec![1, 2, 3, 4];
        let result = wipe_memory(&mut data);
        assert!(result.is_ok());
        assert_eq!(data, vec![0, 0, 0, 0]);
    }
}
```
## ./src/build/mod.rs

```rust
pub mod identity;
pub mod recipient;
```
## ./src/build/identity.rs

```rust
//! Internal identity generation.

use crate::errors::Result;
use age::x25519::Identity;
pub(crate) fn create_identity() -> Result<Identity> {
    let identity = Identity::generate();
    Ok(identity)
}
```
## ./src/build/recipient.rs

```rust
//! Internal recipient extraction.

use age::x25519::{Identity, Recipient};
pub(crate) fn extract_recipient(identity: &Identity) -> Recipient {
    identity.to_public()
}
```