Skip to main content

SecretManager

Struct SecretManager 

Source
pub struct SecretManager { /* private fields */ }
Expand description

Manages encryption and decryption of secrets using age/X25519.

SecretManager provides a simple interface for encrypting and decrypting sensitive values. It uses the age encryption format with X25519 keys.

Encrypted values are stored in the compact format: ENC[AGE:b64:...]

§Examples

use dotenvage::SecretManager;

// Generate a new key
let manager = SecretManager::generate()?;

// Encrypt a value
let encrypted = manager.encrypt_value("my-secret-token")?;
assert!(SecretManager::is_encrypted(&encrypted));

// Decrypt it back
let decrypted = manager.decrypt_value(&encrypted)?;
assert_eq!(decrypted, "my-secret-token");

Implementations§

Source§

impl SecretManager

Source

pub fn new() -> SecretsResult<Self>

Creates a new SecretManager by loading the key from standard locations.

§Key Loading Order
  1. Auto-discover AGE_KEY_NAME from .env or .env.local files (looks for AGE_KEY_NAME or *_AGE_KEY_NAME)
  2. DOTENVAGE_AGE_KEY environment variable (full identity string)
  3. AGE_KEY environment variable (for compatibility)
  4. EKG_AGE_KEY environment variable (for EKG project compatibility)
  5. OS keychain entry using:
    • Service: DOTENVAGE_KEYCHAIN_SERVICE or dotenvage
    • Account: AGE_KEY_NAME or {CARGO_PKG_NAME}/dotenvage
  6. Key file at path determined by AGE_KEY_NAME (e.g., ~/.local/state/ekg/myproject.key if AGE_KEY_NAME=ekg/myproject)
  7. Default key file: ~/.local/state/{CARGO_PKG_NAME}/dotenvage.key
§Errors

Returns an error if no key can be found or if the key is invalid.

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::new()?;
Source

pub fn generate() -> SecretsResult<Self>

Generates a new random identity.

Use this when creating a new encryption key. You’ll typically want to save this key using save_key or save_key_to_default.

§Errors

This function always succeeds and returns Ok.

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::generate()?;
println!("Public key: {}", manager.public_key_string());
Source

pub fn from_identity(identity: Identity) -> Self

Creates a SecretManager from an existing identity.

Use this when you have an age X25519 identity that you want to use directly.

Source

pub fn from_identity_string(identity: &str) -> SecretsResult<Self>

Creates a SecretManager from an age X25519 identity string.

This constructor keeps the concrete age identity type inside dotenvage, so callers that persist or receive an identity as text do not need to depend on the same age crate version.

§Errors

Returns an error when identity is not a valid age X25519 identity.

§Examples
use dotenvage::SecretManager;

let generated = SecretManager::generate()?;
let loaded = SecretManager::from_identity_string(&generated.identity_string())?;
assert_eq!(loaded.public_key_string(), generated.public_key_string());
Source

pub fn public_key(&self) -> Recipient

Gets the public key (recipient) corresponding to this identity.

The public key can be shared with others who want to encrypt values that only you can decrypt.

Source

pub fn public_key_string(&self) -> String

Gets the public key as a string in age format (starts with age1).

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::generate()?;
let public_key = manager.public_key_string();
assert!(public_key.starts_with("age1"));
Source

pub fn encrypt_value(&self, plaintext: &str) -> SecretsResult<String>

Encrypts a plaintext value and wraps it in the format ENC[AGE:b64:...].

The encrypted value can be safely stored in .env files and version control.

§Errors

Returns an error if encryption fails.

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::generate()?;
let encrypted = manager.encrypt_value("sk_live_abc123")?;
assert!(encrypted.starts_with("ENC[AGE:b64:"));
Source

pub fn decrypt_value(&self, value: &str) -> SecretsResult<String>

Decrypts a value if it’s encrypted; otherwise returns it unchanged.

This method automatically detects whether a value is encrypted by checking for the ENC[AGE:b64:...] prefix or the legacy armor format. If the value is not encrypted, it’s returned as-is.

§Supported Formats
  • Compact: ENC[AGE:b64:...] (recommended)
  • Legacy: -----BEGIN AGE ENCRYPTED FILE-----
§Errors

Returns an error if the value is encrypted but decryption fails (e.g., wrong key, corrupted data).

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::generate()?;

// Decrypt an encrypted value
let encrypted = manager.encrypt_value("secret")?;
let decrypted = manager.decrypt_value(&encrypted)?;
assert_eq!(decrypted, "secret");

// Pass through unencrypted values
let plain = manager.decrypt_value("not-encrypted")?;
assert_eq!(plain, "not-encrypted");
Source

pub fn is_encrypted(value: &str) -> bool

Checks if a value is in a recognized encrypted format.

Returns true if the value starts with ENC[AGE:b64: or the legacy age armor format.

§Examples
use dotenvage::SecretManager;

assert!(SecretManager::is_encrypted(
    "ENC[AGE:b64:YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+...]"
));
assert!(!SecretManager::is_encrypted("plaintext"));
Source

pub fn save_key(&self, path: impl AsRef<Path>) -> SecretsResult<()>

Saves the private identity to a file with restricted permissions.

On Unix systems, the file permissions are set to 0o600 (readable and writable only by the owner).

§Errors

Returns an error if the file cannot be created or written.

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::generate()?;
manager.save_key("my-key.txt")?;
Source

pub fn save_key_to_default(&self) -> SecretsResult<PathBuf>

Saves the key to the default path and returns that path.

The default path is typically ~/.local/state/dotenvage/dotenvage.key on Unix systems.

§Errors

Returns an error if the file cannot be created or written.

§Examples
use dotenvage::SecretManager;

let manager = SecretManager::generate()?;
let path = manager.save_key_to_default()?;
println!("Key saved to: {}", path.display());
Source

pub fn save_key_to_os_keychain(&self) -> SecretsResult<(String, String)>

Saves the private key to the OS keychain.

Uses:

  • Service: DOTENVAGE_KEYCHAIN_SERVICE or dotenvage
  • Account: AGE_KEY_NAME or {CARGO_PKG_NAME}/dotenvage

Returns the (service, account) pair used.

§Errors

Returns an error if the key cannot be saved to the OS keychain.

Source

pub fn save_key_to_system_store(&self) -> SecretsResult<KeyLocation>

Saves this key to the system-level credential store.

  • macOS: System Keychain (/Library/Keychains/System.keychain)
  • Linux: /etc/dotenvage/<key-name>.key
  • Windows: %ProgramData%\dotenvage\<key-name>.key

Requires elevated privileges (sudo/admin).

§Errors

Returns SecretsError::InsufficientPrivileges if the process lacks write access to the system store.

Source

pub fn save_key_to_system_store_as( &self, key_name: &str, ) -> SecretsResult<KeyLocation>

Saves this key to the system-level store with an explicit key name.

§Errors

Returns SecretsError::InsufficientPrivileges if the process lacks write access to the system store.

Source

pub fn generate_and_save(options: KeyGenOptions) -> SecretsResult<KeyGenResult>

Generates a new key and saves it to the specified store(s).

This is the programmatic equivalent of dotenvage keygen --store <target>.

§Errors

Returns an error if key generation or saving fails, or if a key already exists and force is not set.

§Examples
use dotenvage::{
    KeyGenOptions,
    KeyStoreTarget,
    SecretManager,
};

let result = SecretManager::generate_and_save(KeyGenOptions {
    target: KeyStoreTarget::OsKeychain,
    key_name: Some("ekg/wwkg".into()),
    file_path: None,
    force: false,
})?;
println!("Public key: {}", result.public_key);
Source

pub fn load_from_system_store() -> SecretsResult<Self>

Loads the key specifically from the system-level store.

Unlike new which tries the full discovery chain, this only checks the system store.

§Errors

Returns an error if no key is found in the system store.

Source

pub fn load_from_user(username: &str) -> SecretsResult<Self>

Loads a key from another user’s file store.

Resolves the key file path for ~<username>/.local/state/... based on the current AGE_KEY_NAME. This is intended for use during sudo operations where the invoking user’s key needs to be read by the elevated process.

§Errors

Returns an error if the user’s home directory cannot be resolved or no key file is found.

Source

pub fn key_exists_in_os_keychain() -> bool

Checks whether a key exists in the OS user keychain.

Source

pub fn key_exists_in_system_store() -> bool

Checks whether a key exists in the system-level store.

Source

pub fn delete_from_os_keychain() -> SecretsResult<()>

Deletes the key from the OS user keychain.

§Errors

Returns an error if the deletion fails. Does not error if no key exists.

Source

pub fn system_store_path() -> PathBuf

Returns the system store path for the current platform and key name.

  • macOS: /Library/Keychains/System.keychain
  • Linux: /etc/dotenvage/<key-name>.key
  • Windows: %ProgramData%\dotenvage\<key-name>.key
Source

pub fn load_key() -> SecretsResult<Self>

Loads the identity from standard locations.

This is called internally by new.

§Key Loading Priority
  1. Read .env files to discover AGE_KEY_NAME (or *_AGE_KEY_NAME) for project-specific keys
  2. DOTENVAGE_AGE_KEY env var (full identity string)
  3. AGE_KEY env var (full identity string)
  4. EKG_AGE_KEY env var (for EKG project compatibility)
  5. OS user keychain (via keyring crate)
  6. System-level store (macOS System Keychain, or /etc/dotenvage/<key>.key on Linux, %ProgramData%\dotenvage\<key>.key on Windows)
  7. Key file at path determined by AGE_KEY_NAME from .env or environment
  8. Default key file: ~/.local/state/{CARGO_PKG_NAME or "dotenvage"}/dotenvage.key
§Errors

Returns an error if no key can be found in any of the standard locations or if the key file/string is invalid.

Source

pub fn discover_age_key_name_from_env_files() -> SecretsResult<()>

Attempts to discover AGE_KEY_NAME from .env files in the current directory.

This reads .env files (without decryption) to find AGE_KEY_NAME or *_AGE_KEY_NAME variables and sets them in the environment so they can be used for key path resolution.

Priority order for .env files:

  1. .env.local
  2. .env
§Errors

Returns an error if an AGE key name variable (e.g., EKG_AGE_KEY_NAME) is found but encrypted. AGE key name variables must be plaintext because they are needed for key discovery, which happens before decryption.

Source

pub fn identity_string(&self) -> String

Returns the raw identity string (AGE-SECRET-KEY-1...).

Use this when you need to embed the key in a service definition for environments where keychain access is unavailable (e.g., containers). Handle the returned string carefully — it is the private key in plaintext.

Source

pub fn key_path_from_env_or_default() -> PathBuf

Returns the key path based on AGE_KEY_NAME or project default.

§Priority:
  1. If AGE_KEY_NAME is set in environment (e.g., from .env), use it
  2. Otherwise default to {CARGO_PKG_NAME}/dotenvage
§Path Construction:
  • XDG-compliant: $XDG_STATE_HOME/{name}.key
  • Fallback: ~/.local/state/{name}.key
§Examples

With AGE_KEY_NAME=myapp/production in .env:

  • Returns: ~/.local/state/myapp/production.key

Without AGE_KEY_NAME (default for “ekg-backend” crate):

  • Returns: ~/.local/state/ekg-backend/dotenvage.key
Source

pub fn default_key_path() -> PathBuf

Returns the default key path (for backward compatibility).

Prefer using key_path_from_env_or_default() which respects AGE_KEY_NAME.

§Examples
use dotenvage::SecretManager;

let path = SecretManager::default_key_path();
println!("Default key path: {}", path.display());

Trait Implementations§

Source§

impl Clone for SecretManager

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V