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,
9    client::{encryption_settings::EncryptionSettingsError, internal::UserKeyState},
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        UserKeyState {
38            private_key: key_pair.private.clone(),
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            signing_key: None,
42            security_state: None,
43        },
44    )?;
45
46    client
47        .internal
48        .set_login_method(crate::client::LoginMethod::User(
49            crate::client::UserLoginMethod::Username {
50                client_id: "".to_owned(),
51                email,
52                kdf: Kdf::default(),
53            },
54        ));
55
56    Ok(RegisterTdeKeyResponse {
57        private_key: key_pair.private,
58        public_key: key_pair.public,
59
60        admin_reset,
61        device_key,
62    })
63}
64
65#[allow(missing_docs)]
66#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
67pub struct RegisterTdeKeyResponse {
68    pub private_key: EncString,
69    pub public_key: B64,
70
71    pub admin_reset: UnsignedSharedKey,
72    pub device_key: Option<TrustDeviceResponse>,
73}