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
impl SecretManager
Sourcepub fn new() -> SecretsResult<Self>
pub fn new() -> SecretsResult<Self>
Creates a new SecretManager by loading the key from standard
locations.
§Key Loading Order
- Auto-discover
AGE_KEY_NAMEfrom.envor.env.localfiles (looks forAGE_KEY_NAMEor*_AGE_KEY_NAME) DOTENVAGE_AGE_KEYenvironment variable (full identity string)AGE_KEYenvironment variable (for compatibility)EKG_AGE_KEYenvironment variable (for EKG project compatibility)- OS keychain entry using:
- Service:
DOTENVAGE_KEYCHAIN_SERVICEordotenvage - Account:
AGE_KEY_NAMEor{CARGO_PKG_NAME}/dotenvage
- Service:
- Key file at path determined by
AGE_KEY_NAME(e.g.,~/.local/state/ekg/myproject.keyifAGE_KEY_NAME=ekg/myproject) - 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()?;Sourcepub fn generate() -> SecretsResult<Self>
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());Sourcepub fn from_identity(identity: Identity) -> Self
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.
Sourcepub fn from_identity_string(identity: &str) -> SecretsResult<Self>
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());Sourcepub fn public_key(&self) -> Recipient
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.
Sourcepub fn public_key_string(&self) -> String
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"));Sourcepub fn encrypt_value(&self, plaintext: &str) -> SecretsResult<String>
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:"));Sourcepub fn decrypt_value(&self, value: &str) -> SecretsResult<String>
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");Sourcepub fn is_encrypted(value: &str) -> bool
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"));Sourcepub fn save_key(&self, path: impl AsRef<Path>) -> SecretsResult<()>
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")?;Sourcepub fn save_key_to_default(&self) -> SecretsResult<PathBuf>
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());Sourcepub fn save_key_to_os_keychain(&self) -> SecretsResult<(String, String)>
pub fn save_key_to_os_keychain(&self) -> SecretsResult<(String, String)>
Saves the private key to the OS keychain.
Uses:
- Service:
DOTENVAGE_KEYCHAIN_SERVICEordotenvage - Account:
AGE_KEY_NAMEor{CARGO_PKG_NAME}/dotenvage
Returns the (service, account) pair used.
§Errors
Returns an error if the key cannot be saved to the OS keychain.
Sourcepub fn save_key_to_system_store(&self) -> SecretsResult<KeyLocation>
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.
Sourcepub fn save_key_to_system_store_as(
&self,
key_name: &str,
) -> SecretsResult<KeyLocation>
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.
Sourcepub fn generate_and_save(options: KeyGenOptions) -> SecretsResult<KeyGenResult>
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);Sourcepub fn load_from_system_store() -> SecretsResult<Self>
pub fn load_from_system_store() -> SecretsResult<Self>
Sourcepub fn load_from_user(username: &str) -> SecretsResult<Self>
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.
Sourcepub fn key_exists_in_os_keychain() -> bool
pub fn key_exists_in_os_keychain() -> bool
Checks whether a key exists in the OS user keychain.
Sourcepub fn key_exists_in_system_store() -> bool
pub fn key_exists_in_system_store() -> bool
Checks whether a key exists in the system-level store.
Sourcepub fn delete_from_os_keychain() -> SecretsResult<()>
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.
Sourcepub fn system_store_path() -> PathBuf
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
Sourcepub fn load_key() -> SecretsResult<Self>
pub fn load_key() -> SecretsResult<Self>
Loads the identity from standard locations.
This is called internally by new.
§Key Loading Priority
- Read .env files to discover
AGE_KEY_NAME(or*_AGE_KEY_NAME) for project-specific keys DOTENVAGE_AGE_KEYenv var (full identity string)AGE_KEYenv var (full identity string)EKG_AGE_KEYenv var (for EKG project compatibility)- OS user keychain (via
keyringcrate) - System-level store (macOS System Keychain, or
/etc/dotenvage/<key>.keyon Linux,%ProgramData%\dotenvage\<key>.keyon Windows) - Key file at path determined by
AGE_KEY_NAMEfrom .env or environment - 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.
Sourcepub fn discover_age_key_name_from_env_files() -> SecretsResult<()>
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:
- .env.local
- .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.
Sourcepub fn identity_string(&self) -> String
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.
Sourcepub fn key_path_from_env_or_default() -> PathBuf
pub fn key_path_from_env_or_default() -> PathBuf
Returns the key path based on AGE_KEY_NAME or project default.
§Priority:
- If
AGE_KEY_NAMEis set in environment (e.g., from .env), use it - 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
Sourcepub fn default_key_path() -> PathBuf
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());