From 4663cffb9695f3cbf02cf621f18e6bcad287e4cc Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sun, 8 Dec 2019 12:12:03 -0800 Subject: [PATCH] yubikey: add `open_by_serial` method Support for opening a `YubiKey` with a specific serial number. --- src/yubikey.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/yubikey.rs b/src/yubikey.rs index 7926670..3ba012d 100644 --- a/src/yubikey.rs +++ b/src/yubikey.rs @@ -159,8 +159,8 @@ impl YubiKey { /// Returns an error if there is more than one YubiKey detected. /// /// If you need to operate in environments with more than one YubiKey - /// attached to the same system, use [`yubikey_piv::Readers`] to select - /// from the available PC/SC readers connected. + /// attached to the same system, use [`YubiKey::open_by_serial`] or + ///[`yubikey_piv::Readers`] to select from the available PC/SC readers. pub fn open() -> Result { let mut readers = Readers::open()?; let mut reader_iter = readers.iter()?; @@ -178,6 +178,25 @@ impl YubiKey { Err(Error::NotFound) } + /// Open a YubiKey with a specific serial number. + pub fn open_by_serial(serial: Serial) -> Result { + let mut readers = Readers::open()?; + + for reader in readers.iter()? { + let mut yubikey = match reader.open() { + Ok(yk) => yk, + Err(_) => continue, + }; + + if serial == yubikey.serial() { + return Ok(yubikey); + } + } + + error!("no YubiKey detected with serial: {}", serial); + Err(Error::NotFound) + } + /// Reconnect to a YubiKey #[cfg(feature = "untested")] pub fn reconnect(&mut self) -> Result<(), Error> {