bitwarden_core/auth/
tde.rs

1use base64::{engine::general_purpose::STANDARD, Engine};
2use bitwarden_crypto::{
3    AsymmetricPublicCryptoKey, DeviceKey, EncString, Kdf, SpkiPublicKeyBytes, SymmetricCryptoKey,
4    TrustDeviceResponse, UnsignedSharedKey, UserKey,
5};
6
7use crate::{client::encryption_settings::EncryptionSettingsError, Client};
8
9/// This function generates a new user key and key pair, initializes the client's crypto with the
10/// generated user key, and encrypts the user key with the organization public key for admin
11/// password reset. If remember_device is true, it also generates a device key.
12pub(super) fn make_register_tde_keys(
13    client: &Client,
14    email: String,
15    org_public_key: String,
16    remember_device: bool,
17) -> Result<RegisterTdeKeyResponse, EncryptionSettingsError> {
18    let public_key = AsymmetricPublicCryptoKey::from_der(&SpkiPublicKeyBytes::from(
19        STANDARD.decode(org_public_key)?,
20    ))?;
21
22    let user_key = UserKey::new(SymmetricCryptoKey::make_aes256_cbc_hmac_key());
23    let key_pair = user_key.make_key_pair()?;
24
25    let admin_reset = UnsignedSharedKey::encapsulate_key_unsigned(&user_key.0, &public_key)?;
26
27    let device_key = if remember_device {
28        Some(DeviceKey::trust_device(&user_key.0)?)
29    } else {
30        None
31    };
32
33    client
34        .internal
35        .set_login_method(crate::client::LoginMethod::User(
36            crate::client::UserLoginMethod::Username {
37                client_id: "".to_owned(),
38                email,
39                kdf: Kdf::default(),
40            },
41        ));
42    client.internal.initialize_user_crypto_decrypted_key(
43        user_key.0,
44        key_pair.private.clone(),
45        // Note: Signing keys are not supported on registration yet. This needs to be changed as
46        // soon as registration is supported.
47        None,
48    )?;
49
50    Ok(RegisterTdeKeyResponse {
51        private_key: key_pair.private,
52        public_key: key_pair.public,
53
54        admin_reset,
55        device_key,
56    })
57}
58
59#[allow(missing_docs)]
60#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
61pub struct RegisterTdeKeyResponse {
62    pub private_key: EncString,
63    pub public_key: String,
64
65    pub admin_reset: UnsignedSharedKey,
66    pub device_key: Option<TrustDeviceResponse>,
67}