From e9ac1e3b5bf46ce8cbdd30fbbb64d38ff0b71cd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=CC=81=20Bispo?= Date: Thu, 13 Jul 2023 15:41:08 +0100 Subject: [PATCH] [PM-2297] Add DecryptUserKeyWithDeviceKey method --- .../Abstractions/IDeviceTrustCryptoService.cs | 1 + src/Core/Services/DeviceTrustCryptoService.cs | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/Core/Abstractions/IDeviceTrustCryptoService.cs b/src/Core/Abstractions/IDeviceTrustCryptoService.cs index 7410b8da4..4335528f6 100644 --- a/src/Core/Abstractions/IDeviceTrustCryptoService.cs +++ b/src/Core/Abstractions/IDeviceTrustCryptoService.cs @@ -10,5 +10,6 @@ namespace Bit.Core.Abstractions Task TrustDeviceIfNeededAsync(); Task GetShouldTrustDeviceAsync(); Task SetShouldTrustDeviceAsync(bool value); + Task DecryptUserKeyWithDeviceKey(string encryptedDevicePrivateKey, string encryptedUserKey); } } diff --git a/src/Core/Services/DeviceTrustCryptoService.cs b/src/Core/Services/DeviceTrustCryptoService.cs index 75d0b2bc3..c8e56c06b 100644 --- a/src/Core/Services/DeviceTrustCryptoService.cs +++ b/src/Core/Services/DeviceTrustCryptoService.cs @@ -99,5 +99,28 @@ namespace Bit.Core.Services await SetShouldTrustDeviceAsync(false); return response; } + + // TODO: Add proper types to parameters once we have them coming down from server + public async Task DecryptUserKeyWithDeviceKey(string encryptedDevicePrivateKey, string encryptedUserKey) + { + // Get device key + var existingDeviceKey = await GetDeviceKeyAsync(); + + if (existingDeviceKey == null) + { + // User doesn't have a device key anymore so device is untrusted + return null; + } + + // Attempt to decrypt encryptedDevicePrivateKey with device key + var devicePrivateKey = await _cryptoService.DecryptToBytesAsync( + new EncString(encryptedDevicePrivateKey), + existingDeviceKey + ); + + // Attempt to decrypt encryptedUserDataKey with devicePrivateKey + var userKey = await _cryptoService.RsaDecryptAsync(encryptedUserKey, devicePrivateKey); + return new SymmetricCryptoKey(userKey); + } } }