Skip to main content

build_keypair

Function build_keypair 

Source
pub fn build_keypair() -> Result<KeyPair>
Expand description

Generates a new age X25519 key pair.

This is the recommended way to create a KeyPair. It performs the following steps securely and automatically:

  1. Generate a fresh identity using the age crate. The identity is created with randomness sourced from the operating system’s secure random number generator (e.g. /dev/urandom on Linux, getrandom).
  2. Extract the public and secret halves from the identity. The secret is temporarily exposed in a local variable which is immediately moved into a SecretKey that guarantees zeroization on drop.
  3. Validate both keys – the public key is checked for the "age1" prefix, the secret key for "AGE-SECRET-KEY-1". This step acts as a safety net; because the strings originate from the age crate they are expected to be valid, but the check catches potential internal bugs early.
  4. Assemble the KeyPair and return it to the caller.

The entire operation is infallible in practice – Identity::generate does not return a Result. The only possible failures are the validation steps, which would indicate a serious bug in the age library or this crate.

§Returns

  • Ok(KeyPair) – a newly generated key pair ready for encryption and decryption.
  • Err(Error::Validation(...)) – if the generated key strings fail the prefix checks (should never happen in practice).

§Security properties

  • The secret key is automatically zeroized when the KeyPair (or its SecretKey field) is dropped. No additional cleanup is needed.
  • The function itself holds the raw secret string for a minimal amount of time; it is moved directly into a [Zeroizing]-backed container.
  • The randomness source is the same as the one used by the age CLI tool and is suitable for production use.

§Examples

use age_setup::build_keypair;

let kp = build_keypair()?;
assert!(kp.public.expose().starts_with("age1"));
assert!(kp.secret.expose_secret().starts_with("AGE-SECRET-KEY-1"));