Struct 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

pub fn decrypt_init( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, ) -> Result<()>

Starts new multi-part decryption operation

Source

pub fn decrypt_update(&self, encrypted_data: &[u8]) -> Result<Vec<u8>>

Continues an ongoing multi-part decryption operation, taking in the next part of the encrypted data and returning its decryption

Source

pub fn decrypt_final(&self) -> Result<Vec<u8>>

Finalizes ongoing multi-part decryption operation, returning any remaining bytes in the decrypted data

Source§

impl Session

Source

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

Single-part digesting operation

Source

pub fn digest_init(&self, m: &Mechanism<'_>) -> Result<()>

Starts new multi-part digesting operation

Source

pub fn digest_update(&self, data: &[u8]) -> Result<()>

Continues an ongoing multi-part digesting operation, taking in the next part of the data to digest

Source

pub fn digest_key(&self, key: ObjectHandle) -> Result<()>

Continues an ongoing multi-part digesting operation, using the value of a secret key as input

Source

pub fn digest_final(&self) -> Result<Vec<u8>>

Finalizes ongoing multi-part digest operation, returning the digest

Source§

impl Session

Source

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

Single-part encryption operation

Source

pub fn encrypt_init( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, ) -> Result<()>

Starts new multi-part encryption operation

Source

pub fn encrypt_update(&self, data: &[u8]) -> Result<Vec<u8>>

Continues an ongoing multi-part encryption operation, taking in the next part of the data and returning its encryption

Source

pub fn encrypt_final(&self) -> Result<Vec<u8>>

Finalizes ongoing multi-part encryption operation, returning any remaining bytes in the encrypted data

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 message_decrypt_init( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, ) -> Result<()>

Prepare a session for one or more Message-based decryption using the same mechanism and key

Source

pub fn decrypt_message( &self, param: &MessageParam<'_>, aad: &[u8], encrypted_data: &[u8], ) -> Result<Vec<u8>>

Decrypts a message in single part

Source

pub fn decrypt_message_begin( &self, param: MessageParam<'_>, aad: &[u8], ) -> Result<()>

Begin multi-part message decryption operation

Source

pub fn decrypt_message_next( &self, param: MessageParam<'_>, encrypted_data: &[u8], end: bool, ) -> Result<Vec<u8>>

Continue mutli-part message decryption operation

Source

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

Finishes Message-based decryption process

Source§

impl Session

Source

pub fn message_encrypt_init( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, ) -> Result<()>

Prepare a session for one or more Message-based encryption using the same mechanism and key

Source

pub fn encrypt_message( &self, param: &MessageParam<'_>, aad: &[u8], data: &[u8], ) -> Result<Vec<u8>>

Encrypts a message in single part

Source

pub fn encrypt_message_begin( &self, param: MessageParam<'_>, aad: &[u8], ) -> Result<()>

Begin multi-part message encryption operation

Source

pub fn encrypt_message_next( &self, param: MessageParam<'_>, data: &[u8], end: bool, ) -> Result<Vec<u8>>

Continue mutli-part message encryption operation

Source

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

Finishes Message-based encryption process

Source§

impl Session

Source

pub fn iter_objects( &self, template: &[Attribute], ) -> Result<ObjectHandleIterator<'_>>

Iterate over session objects matching a template.

§Arguments
  • template - The template to match objects against
§Returns

This function will return a Result<ObjectHandleIterator> that can be used to iterate over the objects matching the template. Note that the cache size is managed internally and set to a default value (10)

§See also
Source

pub fn iter_objects_with_cache_size( &self, template: &[Attribute], cache_size: NonZeroUsize, ) -> Result<ObjectHandleIterator<'_>>

Iterate over session objects matching a template, with cache size

§Arguments
  • template - The template to match objects against
  • cache_size - The number of objects to cache (type is NonZeroUsize)
§Returns

This function will return a Result<ObjectHandleIterator> that can be used to iterate over the objects matching the template. The cache size corresponds to the size of the array provided to C_FindObjects().

§See also
Source

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

Search for session objects matching a template

§Arguments
  • template - A reference to Attribute of search parameters that will be used to find objects.
§Returns

Upon success, a vector of ObjectHandle wrapped in a Result. Upon failure, the first error encountered.

§Note

It is a convenience method that will call Session::iter_objects and collect the results.

§See also
§Example
// Get handles to all of the x509 certificates on the card
let search = vec![Attribute::Class(ObjectClass::CERTIFICATE), Attribute::CertificateType(CertificateType::X_509)];
for handle in session.find_objects(&search)? {
    // each cert: get the "value" which will be the raw certificate data
    for value in session.get_attributes(handle, &[AttributeType::Value])? {
       if let Attribute::Value(value) = value {
           println!("Certificate value: {value:?}");
       }
    }
}
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 copy_object( &self, object: ObjectHandle, template: &[Attribute], ) -> Result<ObjectHandle>

Copy an object

A template can be provided to change some attributes of the new object, when allowed.

§Arguments
  • object - The ObjectHandle used to reference the object to copy
  • template - new values for any attributes of the object that can ordinarily be modified check out PKCS#11 documentation for details
§Returns

This function will return a new ObjectHandle that references the newly created 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("TEST_PKCS11_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().first() {
    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: &[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 sign_init( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, ) -> Result<()>

Starts new multi-part signing operation

Source

pub fn sign_update(&self, data: &[u8]) -> Result<()>

Continues an ongoing multi-part signing operation, taking in the next part of the data to sign

Source

pub fn sign_final(&self) -> Result<Vec<u8>>

Finalizes ongoing multi-part signing operation, returning the signature

Source

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

Verify data in single-part

Source

pub fn verify_init( &self, mechanism: &Mechanism<'_>, key: ObjectHandle, ) -> Result<()>

Starts new multi-part verifying operation

Source

pub fn verify_update(&self, data: &[u8]) -> Result<()>

Continues an ongoing multi-part verifying operation, taking in the next part of the data to verify

Source

pub fn verify_final(&self, signature: &[u8]) -> Result<()>

Finalizes ongoing multi-part verifying operation, returning Ok only if the signature verifies

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. Read more
Source§

impl UpperHex for Session

Source§

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

Formats the value using the given formatter. Read more
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§

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>,

Source§

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>,

Source§

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.