Skip to main content

bitwarden_core/auth/
tde.rs

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