bitwarden_core/auth/
tde.rs

1use bitwarden_crypto::{
2    AsymmetricPublicCryptoKey, DeviceKey, EncString, Kdf, SpkiPublicKeyBytes, SymmetricCryptoKey,
3    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) 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 =
22        AsymmetricPublicCryptoKey::from_der(&SpkiPublicKeyBytes::from(&org_public_key))?;
23
24    let user_key = UserKey::new(SymmetricCryptoKey::make_aes256_cbc_hmac_key());
25    let key_pair = user_key.make_key_pair()?;
26
27    let admin_reset = UnsignedSharedKey::encapsulate_key_unsigned(&user_key.0, &public_key)?;
28
29    let device_key = if remember_device {
30        Some(DeviceKey::trust_device(&user_key.0)?)
31    } else {
32        None
33    };
34
35    client.internal.initialize_user_crypto_decrypted_key(
36        user_key.0,
37        // TODO (https://bitwarden.atlassian.net/browse/PM-21771) Signing keys are not supported on registration yet. This needs to be changed as
38        // soon as registration is supported.
39        WrappedAccountCryptographicState::V1 {
40            private_key: key_pair.private.clone(),
41        },
42    )?;
43
44    client
45        .internal
46        .set_login_method(crate::client::LoginMethod::User(
47            crate::client::UserLoginMethod::Username {
48                client_id: "".to_owned(),
49                email,
50                kdf: Kdf::default(),
51            },
52        ));
53
54    Ok(RegisterTdeKeyResponse {
55        private_key: key_pair.private,
56        public_key: key_pair.public,
57
58        admin_reset,
59        device_key,
60    })
61}
62
63#[allow(missing_docs)]
64#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
65pub struct RegisterTdeKeyResponse {
66    pub private_key: EncString,
67    pub public_key: B64,
68
69    pub admin_reset: UnsignedSharedKey,
70    pub device_key: Option<TrustDeviceResponse>,
71}