Documentation
//! Helpers for password-locked secret key packets

use minipgp6_lock::UnlockedSoftwareKey;
use minipgp6_packet::packet::secret_key::SecretKey;

/// If `key` is not password locked, return a `UnlockedSoftwareKey`
pub fn is_unlocked(key: &SecretKey) -> Option<UnlockedSoftwareKey<'_>> {
    if !key.is_locked() {
        // FIXME: make a nicer API for this in minipgp6_lock?
        UnlockedSoftwareKey::from(key, None).ok()
    } else {
        None
    }
}

/// Try to unlock a secret key packet with a password
pub fn try_unlock_with_password<'a>(
    key: &'a SecretKey,
    password: &[u8],
) -> Option<UnlockedSoftwareKey<'a>> {
    try_unlock_with_passwords(key, &[password])
}

/// Try to unlock a secret key packet with a list of passwords
pub fn try_unlock_with_passwords<'a>(
    key: &'a SecretKey,
    passwords: &[&[u8]],
) -> Option<UnlockedSoftwareKey<'a>> {
    if let Some(unlocked) = is_unlocked(key) {
        Some(unlocked)
    } else {
        for password in passwords {
            if let Ok(unlocked) = UnlockedSoftwareKey::from(key, Some(password)) {
                return Some(unlocked);
            }
        }

        None
    }
}