Struct cryptoki::session::Session

source ·
pub struct Session { /* private fields */ }
Expand description

Type that identifies a session

It will automatically get closed (and logout) on drop. Session does not implement Sync to prevent the same Session instance to be used from multiple threads. A Session needs to be created in its own thread or to be passed by ownership to another thread.

Implementations§

source§

impl Session

source

pub fn decrypt( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, encrypted_data: &[u8] ) -> Result<Vec<u8>>

Single-part decryption operation

source§

impl Session

source

pub fn digest(&self, m: &Mechanism<'_>, data: &[u8]) -> Result<Vec<u8>>

Single-part digesting operation

source§

impl Session

source

pub fn encrypt( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, data: &[u8] ) -> Result<Vec<u8>>

Single-part encryption operation

source§

impl Session

source

pub fn generate_key( &self, mechanism: &Mechanism<'_>, template: &[Attribute] ) -> Result<ObjectHandle>

Generate a secret key

source

pub fn generate_key_pair( &self, mechanism: &Mechanism<'_>, pub_key_template: &[Attribute], priv_key_template: &[Attribute] ) -> Result<(ObjectHandle, ObjectHandle)>

Generate a public/private key pair

source

pub fn derive_key( &self, mechanism: &Mechanism<'_>, base_key: ObjectHandle, template: &[Attribute] ) -> Result<ObjectHandle>

Derives a key from a base key

source

pub fn wrap_key( &self, mechanism: &Mechanism<'_>, wrapping_key: ObjectHandle, key: ObjectHandle ) -> Result<Vec<u8>>

Wrap key

source

pub fn unwrap_key( &self, mechanism: &Mechanism<'_>, unwrapping_key: ObjectHandle, wrapped_key: &[u8], template: &[Attribute] ) -> Result<ObjectHandle>

Unwrap previously wrapped key

source§

impl Session

source

pub fn find_objects(&self, template: &[Attribute]) -> Result<Vec<ObjectHandle>>

Search for session objects matching a template

source

pub fn create_object(&self, template: &[Attribute]) -> Result<ObjectHandle>

Create a new object

source

pub fn destroy_object(&self, object: ObjectHandle) -> Result<()>

Destroy an object

source

pub fn get_attribute_info( &self, object: ObjectHandle, attributes: &[AttributeType] ) -> Result<Vec<AttributeInfo>>

Get the attribute info of an object: if the attribute is present and its size.

§Arguments
  • object - The ObjectHandle used to reference the object
  • attributes - The list of attributes to get the information of
§Returns

This function will return a Vector of AttributeInfo enums that will either contain the size of the requested attribute, AttributeInfo::TypeInvalid if the attribute is not a valid type for the object, or AttributeInfo::Sensitive if the requested attribute is sensitive and will not be returned to the user.

The list of returned attributes is 1-to-1 matched with the provided vector of attribute types. If you wish, you may create a hash table simply by:

use cryptoki::context::Pkcs11;
use cryptoki::context::CInitializeArgs;
use cryptoki::object::AttributeType;
use cryptoki::session::UserType;
use cryptoki::types::AuthPin;
use std::collections::HashMap;
use std::env;

let mut pkcs11 = Pkcs11::new(
        env::var("PKCS11_SOFTHSM2_MODULE")
            .unwrap_or_else(|_| "/usr/local/lib/softhsm/libsofthsm2.so".to_string()),
    )
    .unwrap();

pkcs11.initialize(CInitializeArgs::OsThreads).unwrap();
let slot = pkcs11.get_slots_with_token().unwrap().remove(0);

let session = pkcs11.open_ro_session(slot).unwrap();
session.login(UserType::User, Some(&AuthPin::new("fedcba".into())));

let empty_attrib= vec![];
if let Some(object) = session.find_objects(&empty_attrib).unwrap().get(0) {
    let attribute_types = vec![
        AttributeType::Token,
        AttributeType::Private,
        AttributeType::Modulus,
        AttributeType::KeyType,
        AttributeType::Verify,];

    let attribute_info = session.get_attribute_info(*object, &attribute_types).unwrap();

    let hash = attribute_types
        .iter()
        .zip(attribute_info.iter())
        .collect::<HashMap<_, _>>();
}

Alternatively, you can call Session::get_attribute_info_map, found below.

source

pub fn get_attribute_info_map( &self, object: ObjectHandle, attributes: Vec<AttributeType> ) -> Result<HashMap<AttributeType, AttributeInfo>>

Get the attribute info of an object: if the attribute is present and its size.

§Arguments
  • object - The ObjectHandle used to reference the object
  • attributes - The list of attributes to get the information of
§Returns

This function will return a HashMap of AttributeType and AttributeInfo enums that will either contain the size of the requested attribute, AttributeInfo::TypeInvalid if the attribute is not a valid type for the object, or AttributeInfo::Sensitive if the requested attribute is sensitive and will not be returned to the user.

source

pub fn get_attributes( &self, object: ObjectHandle, attributes: &[AttributeType] ) -> Result<Vec<Attribute>>

Get the attributes values of an object. Ignore the unavailable one. One has to call the get_attribute_info method to check which ones are unavailable.

source

pub fn update_attributes( &self, object: ObjectHandle, template: &[Attribute] ) -> Result<()>

Sets the attributes of an object

source§

impl Session

source

pub fn generate_random_slice(&self, random_data: &mut [u8]) -> Result<()>

Generates a random number and sticks it in a slice

§Arguments
  • random_slice - The slice to stick the random data into. The length of the slice represents the number of bytes to obtain from the RBG
source

pub fn generate_random_vec(&self, random_len: u32) -> Result<Vec<u8>>

Generates random data and returns it as a Vec<u8>. The length of the returned Vector will be the amount of random requested, which is random_len.

source

pub fn seed_random(&self, seed: &[u8]) -> Result<()>

Seeds the RNG

source§

impl Session

source

pub fn login(&self, user_type: UserType, pin: Option<&AuthPin>) -> Result<()>

Log a session in.

§Arguments
  • user_type - The type of user to log in as
  • pin - The PIN to use, or None if you wish to use the protected authentication path

NOTE: By passing None into login, you must ensure that the CKF_PROTECTED_AUTHENTICATION_PATH flag is set in the TokenFlags.

source

pub fn login_with_raw( &self, user_type: UserType, pin: &RawAuthPin ) -> Result<()>

Logs a session in using a slice of raw bytes as a PIN. Some dongle drivers allow non UTF-8 characters in the PIN and as a result, we aren’t guaranteed that we can pass in a UTF-8 string to login. Therefore, it’s useful to be able to pass in raw bytes rather than convert a UTF-8 string to bytes.

§Arguments
  • user_type - The type of user to log in as
  • pin - The PIN to use

NOTE: By passing None into login, you must ensure that the CKF_PROTECTED_AUTHENTICATION_PATH flag is set in the TokenFlags.

source

pub fn logout(&self) -> Result<()>

Log a session out

source

pub fn get_session_info(&self) -> Result<SessionInfo>

Returns the information about a session

source§

impl Session

source

pub fn sign( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, data: &[u8] ) -> Result<Vec<u8>>

Sign data in single-part

source

pub fn verify( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, data: &[u8], signature: &[u8] ) -> Result<()>

Verify data in single-part

source§

impl Session

source

pub fn init_pin(&self, pin: &AuthPin) -> Result<()>

Initialize the normal user’s pin for a token

source

pub fn set_pin(&self, old_pin: &AuthPin, new_pin: &AuthPin) -> Result<()>

Changes the PIN of either the currently logged in user or of the CKU_USER if no user is logged in.

source§

impl Session

source

pub fn close(self)

Close a session This will be called on drop as well.

Trait Implementations§

source§

impl Debug for Session

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Session

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Session

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl LowerHex for Session

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter.
source§

impl UpperHex for Session

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter.
source§

impl Send for Session

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<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> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.