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:
- Generate a fresh identity using the
agecrate. The identity is created with randomness sourced from the operating system’s secure random number generator (e.g./dev/urandomon Linux,getrandom). - Extract the public and secret halves from the identity. The secret
is temporarily exposed in a local variable which is immediately moved
into a
SecretKeythat guarantees zeroization on drop. - 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 theagecrate they are expected to be valid, but the check catches potential internal bugs early. - Assemble the
KeyPairand 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 itsSecretKeyfield) 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
ageCLI 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"));