Skip to content

Commit

Permalink
Added new methods to fix issue_275 - get slots with initialized token…
Browse files Browse the repository at this point in the history
…, for PKCS 11 Provider

Signed-off-by: Adriano Pallavicino <[email protected]>
  • Loading branch information
Sven-bg committed Jul 19, 2021
1 parent 2d9ba34 commit 3dc49c0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
43 changes: 41 additions & 2 deletions cryptoki/src/functions/slot_token_management.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Slot and token management functions

use crate::get_pkcs11;
Expand Down Expand Up @@ -47,6 +45,47 @@ impl Pkcs11 {
Ok(slots)
}

/// Get all slots available with a token
pub fn get_slots_with_initialized_token(&self) -> Result<Vec<Slot>> {
let mut slot_count = 0;

unsafe {
Rv::from(get_pkcs11!(self, C_GetSlotList)(
cryptoki_sys::CK_TRUE,
std::ptr::null_mut(),
&mut slot_count,
))
.into_result()?;
}

let mut slots = vec![0; slot_count.try_into()?];

unsafe {
Rv::from(get_pkcs11!(self, C_GetSlotList)(
cryptoki_sys::CK_TRUE,
slots.as_mut_ptr(),
&mut slot_count,
))
.into_result()?;
}

let mut slots: Vec<Slot> = slots.into_iter().map(Slot::new).collect();

// This should always truncate slots.
slots.resize(slot_count.try_into()?, Slot::new(0));

let slots: Vec<Slot> = slots.into_iter().filter_map(|slot| match self.get_token_info(slot) {
Ok(token_info) => if token_info.get_flags().token_initialized() {
Some(Ok(slot))
} else {
None
},
Err(e) => Some(Err(e))
}).collect::<Result<Vec<Slot>>>()?;

Ok(slots)
}

/// Get all slots
pub fn get_all_slots(&self) -> Result<Vec<Slot>> {
let mut slot_count = 0;
Expand Down
6 changes: 6 additions & 0 deletions cryptoki/src/types/slot_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

use crate::{Error, Result};
use cryptoki_sys::{CK_SLOT_ID, CK_TOKEN_INFO};
use crate::types::Flags;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;

Expand Down Expand Up @@ -68,6 +69,11 @@ impl TokenInfo {
.trim_end()
.to_string()
}

/// Returns the Token's flags
pub fn get_flags(&self) -> Flags {
self.val.flags.into()
}
}

impl Deref for TokenInfo {
Expand Down

0 comments on commit 3dc49c0

Please sign in to comment.