1+ use std:: sync:: OnceLock ;
2+
13use chacha20poly1305:: {
24 aead:: { AeadMut , Key , Nonce , OsRng } ,
35 AeadCore , KeyInit , XChaCha20Poly1305 ,
@@ -15,6 +17,28 @@ pub type PlatformKeyStore = keyring::KeyStore;
1517
1618const NONCE_SIZE : usize = 24 ;
1719
20+ /// The global [KeyStore] instance.
21+ ///
22+ /// Normally initialized with the default implementation on first access.
23+ pub static KEY_STORE : OnceLock < Box < dyn KeyStore > > = OnceLock :: new ( ) ;
24+
25+ /// Returns the set [KeyStore] implementation, initializing it with the default if necessary.
26+ pub fn get_key_store < ' a > ( ) -> & ' a Box < dyn KeyStore > {
27+ KEY_STORE . get_or_init ( default_key_store)
28+ }
29+
30+ /// Returns the default [KeyStore] implementation for this platform.
31+ pub fn default_key_store ( ) -> Box < dyn KeyStore > {
32+ #[ cfg( use_keyring) ]
33+ {
34+ return Box :: new ( keyring:: KeyStore ) ;
35+ }
36+ #[ cfg( not( use_keyring) ) ]
37+ {
38+ panic ! ( "Platform not supported!" ) ;
39+ }
40+ }
41+
1842/// Encrypts the given data using the provided key.
1943pub fn encrypt ( data : & [ u8 ] , key : Vec < u8 > ) -> Result < Vec < u8 > , Error > {
2044 let key = Key :: < XChaCha20Poly1305 > :: from_iter ( key) ;
@@ -64,23 +88,23 @@ pub fn namespace() -> Result<String, Error> {
6488}
6589
6690/// A trait for storing and retrieving keys.
67- pub trait KeyStore {
91+ pub trait KeyStore : Send + Sync + ' static {
6892 /// Returns the key with the given name, generating a new one if none exists.
69- fn get_key_or_generate ( name : & str ) -> Result < Vec < u8 > , Error > {
70- let key = Self :: get_key ( name) ?;
93+ fn get_key_or_generate ( & self , name : & str ) -> Result < Vec < u8 > , Error > {
94+ let key = self . get_key ( name) ?;
7195
7296 if let Some ( key) = key {
7397 Ok ( key)
7498 } else {
7599 let key = generate_key ( ) ;
76- Self :: set_key ( name, key. to_vec ( ) ) ?;
100+ self . set_key ( name, key. to_vec ( ) ) ?;
77101 Ok ( key. to_vec ( ) )
78102 }
79103 }
80104
81105 /// Returns the key with the given name, if one exists.
82- fn get_key ( name : & str ) -> Result < Option < Vec < u8 > > , Error > ;
106+ fn get_key ( & self , name : & str ) -> Result < Option < Vec < u8 > > , Error > ;
83107
84108 /// Sets the key with the given name.
85- fn set_key ( name : & str , key : Vec < u8 > ) -> Result < ( ) , Error > ;
109+ fn set_key ( & self , name : & str , key : Vec < u8 > ) -> Result < ( ) , Error > ;
86110}
0 commit comments