Struct KeyStore

Source
pub struct KeyStore<Ids: KeyIds> {
    inner: Arc<RwLock<KeyStoreInner<Ids>>>,
}
Expand description

An in-memory key store that provides a safe and secure way to store keys and use them for encryption/decryption operations. The store API is designed to work only on key identifiers (KeyId). These identifiers are user-defined types that contain no key material, which means the API users don’t have to worry about accidentally leaking keys.

Each store is designed to be used by a single user and should not be shared between users, but the store itself is thread safe and can be cloned to share between threads.


// We need to define our own key identifier types. We provide a macro to make this easier.
key_ids! {
    #[symmetric]
    pub enum SymmKeyId {
        User,
        #[local]
        Local(&'static str)
    }
    #[asymmetric]
    pub enum AsymmKeyId {
        UserPrivate,
    }
    pub Ids => SymmKeyId, AsymmKeyId;
}

// Initialize the store and insert a test key
let store: KeyStore<Ids> = KeyStore::default();

#[allow(deprecated)]
store.context_mut().set_symmetric_key(SymmKeyId::User, SymmetricCryptoKey::generate(rand::thread_rng()));

// Define some data that needs to be encrypted
struct Data(String);
impl IdentifyKey<SymmKeyId> for Data {
   fn key_identifier(&self) -> SymmKeyId {
       SymmKeyId::User
   }
}
impl Encryptable<Ids, SymmKeyId, EncString> for Data {
    fn encrypt(&self, ctx: &mut KeyStoreContext<Ids>, key: SymmKeyId) -> Result<EncString, CryptoError> {
        self.0.encrypt(ctx, key)
    }
}

// Encrypt the data
let decrypted = Data("Hello, World!".to_string());
let encrypted = store.encrypt(decrypted).unwrap();

Fields§

§inner: Arc<RwLock<KeyStoreInner<Ids>>>

Implementations§

Source§

impl<Ids: KeyIds> KeyStore<Ids>

Source

pub fn clear(&self)

Clear all keys from the store. This can be used to clear all keys from memory in case of lock/logout, and is equivalent to destroying the store and creating a new one.

Source

pub fn context(&self) -> KeyStoreContext<'_, Ids>

This is an advanced API, use with care. If you still need to use it, make sure you read this documentation to understand how to use it safely.

Initiate an encryption/decryption context. This context will have read only access to the global keys, and will have its own local key stores with read/write access. This context-local store will be cleared up when the context is dropped.

Some possible use cases for this API and alternative recommendations are:

One of the pitfalls of the current implementations is that keys stored in the context-local store only get cleared automatically when the context is dropped, and not between operations. This means that if you are using the same context for multiple operations, you may want to clear it manually between them.

Source

pub fn context_mut(&self) -> KeyStoreContext<'_, Ids>

This is an advanced API, use with care and ONLY when needing to modify the global keys.

The same pitfalls as Self::context apply here, but with the added risk of accidentally modifying the global keys and leaving the store in an inconsistent state. If you still need to use it, make sure you read this documentation to understand how to use it safely.

Initiate an encryption/decryption context. This context will have MUTABLE access to the global keys, and will have its own local key stores with read/write access. This context-local store will be cleared up when the context is dropped.

The only supported use case for this API is initializing the store with the user’s symetric and private keys, and setting the organization keys. This method will be marked as pub(crate) in the future, once we have a safe API for key initialization and updating.

Source

pub fn decrypt<Key: KeyId, Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key>, Output>( &self, data: &Data, ) -> Result<Output, CryptoError>

Decript a single item using this key store. The key returned by data.key_identifier() must already be present in the store, otherwise this will return an error. This method is not parallelized, and is meant for single item decryption. If you need to decrypt multiple items, use decrypt_list instead.

Source

pub fn encrypt<Key: KeyId, Data: Encryptable<Ids, Key, Output> + IdentifyKey<Key>, Output>( &self, data: Data, ) -> Result<Output, CryptoError>

Encrypt a single item using this key store. The key returned by data.key_identifier() must already be present in the store, otherwise this will return an error. This method is not parallelized, and is meant for single item encryption. If you need to encrypt multiple items, use encrypt_list instead.

Source

pub fn decrypt_list<Key: KeyId, Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync, Output: Send + Sync>( &self, data: &[Data], ) -> Result<Vec<Output>, CryptoError>

Decrypt a list of items using this key store. The keys returned by data[i].key_identifier() must already be present in the store, otherwise this will return an error. This method will try to parallelize the decryption of the items, for better performance on large lists.

Source

pub fn encrypt_list<Key: KeyId, Data: Encryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync, Output: Send + Sync>( &self, data: &[Data], ) -> Result<Vec<Output>, CryptoError>

Encrypt a list of items using this key store. The keys returned by data[i].key_identifier() must already be present in the store, otherwise this will return an error. This method will try to parallelize the encryption of the items, for better performance on large lists. This method is not parallelized, and is meant for single item encryption.

Trait Implementations§

Source§

impl<Ids: Clone + KeyIds> Clone for KeyStore<Ids>

Source§

fn clone(&self) -> KeyStore<Ids>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Ids: KeyIds> Debug for KeyStore<Ids>

KeyStore contains sensitive data, provide a dummy Debug implementation.

Source§

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

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

impl<Ids: KeyIds> Default for KeyStore<Ids>

Create a new key store with the best available implementation for the current platform.

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<Ids> Freeze for KeyStore<Ids>

§

impl<Ids> RefUnwindSafe for KeyStore<Ids>

§

impl<Ids> Send for KeyStore<Ids>

§

impl<Ids> Sync for KeyStore<Ids>

§

impl<Ids> Unpin for KeyStore<Ids>

§

impl<Ids> UnwindSafe for KeyStore<Ids>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
§

unsafe fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
§

unsafe fn consume_handle(handle: Handle) -> Arc<T>

Consume a handle, getting back the initial Arc<> Read more
§

unsafe fn get_arc(handle: Handle) -> Arc<Self>

Get a clone of the Arc<> using a “borrowed” handle. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V