From 11fb36e7e09c47ad2b28076c4521b53bd8c0e8bb Mon Sep 17 00:00:00 2001 From: Bernd Schoolmann Date: Thu, 24 Apr 2025 18:33:37 +0200 Subject: [PATCH] tmp --- .../background/nativeMessaging.background.ts | 5 ++- ...cal-backed-session-storage.service.spec.ts | 16 ++++----- .../local-backed-session-storage.service.ts | 2 +- apps/cli/src/commands/download.command.ts | 2 +- apps/cli/src/commands/get.command.ts | 2 +- .../node-env-secure-storage.service.ts | 6 ++-- .../src/native-message.service.ts | 2 +- .../biometric-message-handler.service.spec.ts | 8 ++--- .../biometric-message-handler.service.ts | 2 +- .../duckduckgo-message-handler.service.ts | 2 +- .../services/rotateable-key-set.service.ts | 2 +- .../services/critical-apps.service.spec.ts | 12 +++---- .../services/critical-apps.service.ts | 6 ++-- .../setup/setup-business-unit.component.ts | 4 +-- .../projects/project.service.ts | 4 +-- .../secrets/secret.service.spec.ts | 4 +-- .../secrets-manager/secrets/secret.service.ts | 10 +++--- .../service-accounts/access/access.service.ts | 2 +- .../service-account.service.ts | 4 +-- .../services/sm-porting-api.service.spec.ts | 4 +-- .../services/sm-porting-api.service.ts | 8 ++--- .../access-policy.service.spec.ts | 4 +-- .../access-policies/access-policy.service.ts | 6 ++-- .../default-collection-admin.service.ts | 4 +-- .../default-collection.service.spec.ts | 2 +- .../services/default-collection.service.ts | 2 +- .../default-vnext-collection.service.spec.ts | 8 ++--- .../default-vnext-collection.service.ts | 2 +- .../vault/components/attachments.component.ts | 4 +-- .../src/vault/components/view.component.ts | 2 +- .../webauthn-login.strategy.spec.ts | 10 +++--- .../webauthn-login.strategy.ts | 2 +- .../pin/pin.service.implementation.ts | 8 ++--- .../common/services/pin/pin.service.spec.ts | 10 +++--- .../domain/encrypted-organization-key.ts | 4 +-- .../src/auth/services/token.service.spec.ts | 6 ++-- .../common/src/auth/services/token.service.ts | 4 +-- .../services/organization-billing.service.ts | 2 +- .../device-trust.service.implementation.ts | 12 +++---- .../services/device-trust.service.spec.ts | 28 +++++++-------- .../services/master-password.service.ts | 10 +++--- .../models/domain/domain-base.spec.ts | 24 +++---------- .../platform/models/domain/enc-string.spec.ts | 34 +++++++------------ .../src/platform/models/domain/enc-string.ts | 16 ++------- .../organization-key-encryptor.spec.ts | 8 ++--- .../organization-key-encryptor.ts | 4 +-- .../cryptography/user-key-encryptor.spec.ts | 8 ++--- .../tools/cryptography/user-key-encryptor.ts | 4 +-- .../src/tools/send/models/domain/send.spec.ts | 2 +- .../src/tools/send/models/domain/send.ts | 3 +- .../tools/send/services/send.service.spec.ts | 2 +- .../src/tools/send/services/send.service.ts | 16 ++++----- .../vault/models/domain/attachment.spec.ts | 9 ++--- .../src/vault/models/domain/attachment.ts | 4 +-- .../src/vault/models/domain/cipher.spec.ts | 9 ++--- libs/common/src/vault/models/domain/cipher.ts | 7 ++-- .../src/vault/models/domain/folder.spec.ts | 2 +- .../src/vault/services/cipher.service.spec.ts | 10 +++--- .../src/vault/services/cipher.service.ts | 26 ++++++-------- .../services/folder/folder.service.spec.ts | 6 ++-- .../vault/services/folder/folder.service.ts | 2 +- .../bitwarden/bitwarden-json-importer.ts | 2 +- ...warden-password-protected-importer.spec.ts | 2 +- .../bitwarden-password-protected-importer.ts | 4 +-- libs/key-management/src/key.service.spec.ts | 15 ++++---- libs/key-management/src/key.service.ts | 5 ++- ...symmetric-key-regeneration.service.spec.ts | 6 ++-- .../src/services/base-vault-export.service.ts | 4 +-- .../individual-vault-export.service.spec.ts | 12 +++---- .../individual-vault-export.service.ts | 4 +-- .../src/services/org-vault-export.service.ts | 2 +- .../src/services/vault-export.service.spec.ts | 6 ++-- .../src/legacy-password-history-decryptor.ts | 2 +- .../local-generator-history.service.spec.ts | 4 +-- .../download-attachment.component.ts | 2 +- 75 files changed, 229 insertions(+), 274 deletions(-) diff --git a/apps/browser/src/background/nativeMessaging.background.ts b/apps/browser/src/background/nativeMessaging.background.ts index d92826765db..7172b98d727 100644 --- a/apps/browser/src/background/nativeMessaging.background.ts +++ b/apps/browser/src/background/nativeMessaging.background.ts @@ -357,7 +357,7 @@ export class NativeMessagingBackground { await this.secureCommunication(); } - return await this.encryptService.encrypt( + return await this.encryptService.encryptString( JSON.stringify(message), this.secureChannel!.sharedSecret!, ); @@ -401,10 +401,9 @@ export class NativeMessagingBackground { return; } message = JSON.parse( - await this.encryptService.decryptToUtf8( + await this.encryptService.decryptString( rawMessage as EncString, this.secureChannel.sharedSecret, - "ipc-desktop-ipc-channel-key", ), ); } else { diff --git a/apps/browser/src/platform/services/local-backed-session-storage.service.spec.ts b/apps/browser/src/platform/services/local-backed-session-storage.service.spec.ts index 1b93e33a94e..854614bbdf7 100644 --- a/apps/browser/src/platform/services/local-backed-session-storage.service.spec.ts +++ b/apps/browser/src/platform/services/local-backed-session-storage.service.spec.ts @@ -46,11 +46,11 @@ describe("LocalBackedSessionStorage", () => { it("returns a decrypted value when one is stored in local storage", async () => { const encrypted = makeEncString("encrypted"); localStorage.internalStore["session_test"] = encrypted.encryptedString; - encryptService.decryptToUtf8.mockResolvedValue(JSON.stringify("decrypted")); + encryptService.decryptString.mockResolvedValue(JSON.stringify("decrypted")); const result = await sut.get("test"); // FIXME: Remove when updating file. Eslint update // eslint-disable-next-line @typescript-eslint/no-unused-expressions - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith( + expect(encryptService.decryptString).toHaveBeenCalledWith( encrypted, sessionKey, "browser-session-key", @@ -61,7 +61,7 @@ describe("LocalBackedSessionStorage", () => { it("caches the decrypted value when one is stored in local storage", async () => { const encrypted = makeEncString("encrypted"); localStorage.internalStore["session_test"] = encrypted.encryptedString; - encryptService.decryptToUtf8.mockResolvedValue(JSON.stringify("decrypted")); + encryptService.decryptString.mockResolvedValue(JSON.stringify("decrypted")); await sut.get("test"); expect(sut["cache"]["test"]).toEqual("decrypted"); }); @@ -69,11 +69,11 @@ describe("LocalBackedSessionStorage", () => { it("returns a decrypted value when one is stored in local storage", async () => { const encrypted = makeEncString("encrypted"); localStorage.internalStore["session_test"] = encrypted.encryptedString; - encryptService.decryptToUtf8.mockResolvedValue(JSON.stringify("decrypted")); + encryptService.decryptString.mockResolvedValue(JSON.stringify("decrypted")); const result = await sut.get("test"); // FIXME: Remove when updating file. Eslint update // eslint-disable-next-line @typescript-eslint/no-unused-expressions - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith( + expect(encryptService.decryptString).toHaveBeenCalledWith( encrypted, sessionKey, "browser-session-key", @@ -84,7 +84,7 @@ describe("LocalBackedSessionStorage", () => { it("caches the decrypted value when one is stored in local storage", async () => { const encrypted = makeEncString("encrypted"); localStorage.internalStore["session_test"] = encrypted.encryptedString; - encryptService.decryptToUtf8.mockResolvedValue(JSON.stringify("decrypted")); + encryptService.decryptString.mockResolvedValue(JSON.stringify("decrypted")); await sut.get("test"); expect(sut["cache"]["test"]).toEqual("decrypted"); }); @@ -104,7 +104,7 @@ describe("LocalBackedSessionStorage", () => { it("returns true when the key is in local storage", async () => { localStorage.internalStore["session_test"] = makeEncString("encrypted").encryptedString; - encryptService.decryptToUtf8.mockResolvedValue(JSON.stringify("decrypted")); + encryptService.decryptString.mockResolvedValue(JSON.stringify("decrypted")); const result = await sut.has("test"); expect(result).toBe(true); }); @@ -119,7 +119,7 @@ describe("LocalBackedSessionStorage", () => { async (nullish) => { localStorage.internalStore["session_test"] = nullish; await expect(sut.has("test")).resolves.toBe(false); - expect(encryptService.decryptToUtf8).not.toHaveBeenCalled(); + expect(encryptService.decryptString).not.toHaveBeenCalled(); }, ); }); diff --git a/apps/browser/src/platform/services/local-backed-session-storage.service.ts b/apps/browser/src/platform/services/local-backed-session-storage.service.ts index 0e6922e3083..c2996d687bd 100644 --- a/apps/browser/src/platform/services/local-backed-session-storage.service.ts +++ b/apps/browser/src/platform/services/local-backed-session-storage.service.ts @@ -118,7 +118,7 @@ export class LocalBackedSessionStorageService return null; } - const valueJson = await this.encryptService.decryptToUtf8( + const valueJson = await this.encryptService.decryptString( new EncString(local), encKey, "browser-session-key", diff --git a/apps/cli/src/commands/download.command.ts b/apps/cli/src/commands/download.command.ts index 01ef675d2a8..472b084f5d7 100644 --- a/apps/cli/src/commands/download.command.ts +++ b/apps/cli/src/commands/download.command.ts @@ -47,7 +47,7 @@ export abstract class DownloadCommand { try { const encBuf = await EncArrayBuffer.fromResponse(response); - const decBuf = await this.encryptService.decryptToBytes(encBuf, key); + const decBuf = await this.encryptService.decryptFileData(encBuf, key); if (process.env.BW_SERVE === "true") { const res = new FileResponse(Buffer.from(decBuf), fileName); return Response.success(res); diff --git a/apps/cli/src/commands/get.command.ts b/apps/cli/src/commands/get.command.ts index 1bdbd051585..a9978aa58f5 100644 --- a/apps/cli/src/commands/get.command.ts +++ b/apps/cli/src/commands/get.command.ts @@ -455,7 +455,7 @@ export class GetCommand extends DownloadCommand { const response = await this.apiService.getCollectionAccessDetails(options.organizationId, id); const decCollection = new CollectionView(response); - decCollection.name = await this.encryptService.decryptToUtf8( + decCollection.name = await this.encryptService.decryptString( new EncString(response.name), orgKey, `orgkey-${options.organizationId}`, diff --git a/apps/cli/src/platform/services/node-env-secure-storage.service.ts b/apps/cli/src/platform/services/node-env-secure-storage.service.ts index 5e31995606f..d3e9cc6f986 100644 --- a/apps/cli/src/platform/services/node-env-secure-storage.service.ts +++ b/apps/cli/src/platform/services/node-env-secure-storage.service.ts @@ -60,8 +60,8 @@ export class NodeEnvSecureStorageService implements AbstractStorageService { const sessionKey = this.getSessionKey(); if (sessionKey == null) { throw new Error("No session key available."); - } - const encValue = await this.encryptService.encryptToBytes( + } + const encValue = await this.encryptService.encryptFileData( Utils.fromB64ToArray(plainValue), sessionKey, ); @@ -80,7 +80,7 @@ export class NodeEnvSecureStorageService implements AbstractStorageService { } const encBuf = EncArrayBuffer.fromB64(encValue); - const decValue = await this.encryptService.decryptToBytes(encBuf, sessionKey); + const decValue = await this.encryptService.decryptFileData(encBuf, sessionKey); if (decValue == null) { this.logService.info("Failed to decrypt."); return null; diff --git a/apps/desktop/native-messaging-test-runner/src/native-message.service.ts b/apps/desktop/native-messaging-test-runner/src/native-message.service.ts index c01d581afe8..f04c5ce54fa 100644 --- a/apps/desktop/native-messaging-test-runner/src/native-message.service.ts +++ b/apps/desktop/native-messaging-test-runner/src/native-message.service.ts @@ -228,7 +228,7 @@ export default class NativeMessageService { key: string, ): Promise { const sharedKey = await this.getSharedKeyForKey(key); - const decrypted = await this.encryptService.decryptToUtf8( + const decrypted = await this.encryptService.decryptString( payload, sharedKey, "native-messaging-session", diff --git a/apps/desktop/src/services/biometric-message-handler.service.spec.ts b/apps/desktop/src/services/biometric-message-handler.service.spec.ts index 0e92e3839fe..4177fd43b87 100644 --- a/apps/desktop/src/services/biometric-message-handler.service.spec.ts +++ b/apps/desktop/src/services/biometric-message-handler.service.spec.ts @@ -221,7 +221,7 @@ describe("BiometricMessageHandlerService", () => { trusted: false, }), ); - encryptService.decryptToUtf8.mockResolvedValue( + encryptService.decryptString.mockResolvedValue( JSON.stringify({ command: "biometricUnlock", messageId: 0, @@ -256,7 +256,7 @@ describe("BiometricMessageHandlerService", () => { ngZone.run.mockReturnValue({ closed: of(true), }); - encryptService.decryptToUtf8.mockResolvedValue( + encryptService.decryptString.mockResolvedValue( JSON.stringify({ command: BiometricsCommands.UnlockWithBiometricsForUser, messageId: 0, @@ -307,7 +307,7 @@ describe("BiometricMessageHandlerService", () => { ngZone.run.mockReturnValue({ closed: of(false), }); - encryptService.decryptToUtf8.mockResolvedValue( + encryptService.decryptString.mockResolvedValue( JSON.stringify({ command: BiometricsCommands.UnlockWithBiometricsForUser, messageId: 0, @@ -354,7 +354,7 @@ describe("BiometricMessageHandlerService", () => { trusted: true, }), ); - encryptService.decryptToUtf8.mockResolvedValue( + encryptService.decryptString.mockResolvedValue( JSON.stringify({ command: BiometricsCommands.UnlockWithBiometricsForUser, messageId: 0, diff --git a/apps/desktop/src/services/biometric-message-handler.service.ts b/apps/desktop/src/services/biometric-message-handler.service.ts index 48026bca388..398c8b9ecc9 100644 --- a/apps/desktop/src/services/biometric-message-handler.service.ts +++ b/apps/desktop/src/services/biometric-message-handler.service.ts @@ -160,7 +160,7 @@ export class BiometricMessageHandlerService { } const message: LegacyMessage = JSON.parse( - await this.encryptService.decryptToUtf8( + await this.encryptService.decryptString( rawMessage as EncString, SymmetricCryptoKey.fromString(sessionSecret), ), diff --git a/apps/desktop/src/services/duckduckgo-message-handler.service.ts b/apps/desktop/src/services/duckduckgo-message-handler.service.ts index e82444be993..deffc7f27f7 100644 --- a/apps/desktop/src/services/duckduckgo-message-handler.service.ts +++ b/apps/desktop/src/services/duckduckgo-message-handler.service.ts @@ -188,7 +188,7 @@ export class DuckDuckGoMessageHandlerService { } try { - let decryptedResult = await this.encryptService.decryptToUtf8( + let decryptedResult = await this.encryptService.decryptString( message.encryptedCommand as EncString, this.duckduckgoSharedSecret, "ddg-shared-key", diff --git a/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts b/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts index ef78e09e6b9..0a150b26ae2 100644 --- a/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts +++ b/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts @@ -58,7 +58,7 @@ export class RotateableKeySetService { throw new Error("failed to rotate key set: newUserKey is required"); } - const publicKey = await this.encryptService.decryptToBytes( + const publicKey = await this.encryptService.unwrapEncapsulationKey( keySet.encryptedPublicKey, oldUserKey, ); diff --git a/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.spec.ts b/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.spec.ts index d2d48edf869..b3e8e11f4f7 100644 --- a/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.spec.ts +++ b/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.spec.ts @@ -59,7 +59,7 @@ describe("CriticalAppsService", () => { { id: "id2", organizationId: "org1", uri: "https://example.org" }, ] as PasswordHealthReportApplicationsResponse[]; - encryptService.encrypt.mockResolvedValue(new EncString("encryptedUrlName")); + encryptService.encryptString.mockResolvedValue(new EncString("encryptedUrlName")); criticalAppsApiService.saveCriticalApps.mockReturnValue(of(response)); // act @@ -67,7 +67,7 @@ describe("CriticalAppsService", () => { // expectations expect(keyService.getOrgKey).toHaveBeenCalledWith("org1"); - expect(encryptService.encrypt).toHaveBeenCalledTimes(2); + expect(encryptService.encryptString).toHaveBeenCalledTimes(2); expect(criticalAppsApiService.saveCriticalApps).toHaveBeenCalledWith(request); }); @@ -95,7 +95,7 @@ describe("CriticalAppsService", () => { { id: "id1", organizationId: "org1", uri: "test" }, ] as PasswordHealthReportApplicationsResponse[]; - encryptService.encrypt.mockResolvedValue(new EncString("encryptedUrlName")); + encryptService.encryptString.mockResolvedValue(new EncString("encryptedUrlName")); criticalAppsApiService.saveCriticalApps.mockReturnValue(of(response)); // act @@ -103,7 +103,7 @@ describe("CriticalAppsService", () => { // expectations expect(keyService.getOrgKey).toHaveBeenCalledWith("org1"); - expect(encryptService.encrypt).toHaveBeenCalledTimes(1); + expect(encryptService.encryptString).toHaveBeenCalledTimes(1); expect(criticalAppsApiService.saveCriticalApps).toHaveBeenCalledWith(request); }); @@ -114,7 +114,7 @@ describe("CriticalAppsService", () => { { id: "id2", organizationId: "org1", uri: "https://example.org" }, ] as PasswordHealthReportApplicationsResponse[]; - encryptService.decryptToUtf8.mockResolvedValue("https://example.com"); + encryptService.decryptString.mockResolvedValue("https://example.com"); criticalAppsApiService.getCriticalApps.mockReturnValue(of(response)); const mockRandomBytes = new Uint8Array(64) as CsprngArray; @@ -125,7 +125,7 @@ describe("CriticalAppsService", () => { flush(); expect(keyService.getOrgKey).toHaveBeenCalledWith(orgId.toString()); - expect(encryptService.decryptToUtf8).toHaveBeenCalledTimes(2); + expect(encryptService.decryptString).toHaveBeenCalledTimes(2); expect(criticalAppsApiService.getCriticalApps).toHaveBeenCalledWith(orgId); })); diff --git a/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.ts b/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.ts index bc8edc17360..b879ef94705 100644 --- a/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.ts +++ b/bitwarden_license/bit-common/src/tools/reports/risk-insights/services/critical-apps.service.ts @@ -81,7 +81,7 @@ export class CriticalAppsService { // add the new entries to the criticalAppsList const updatedList = [...this.criticalAppsList.value]; for (const responseItem of dbResponse) { - const decryptedUrl = await this.encryptService.decryptToUtf8( + const decryptedUrl = await this.encryptService.decryptString( new EncString(responseItem.uri), key, ); @@ -138,7 +138,7 @@ export class CriticalAppsService { const results = response.map(async (r: PasswordHealthReportApplicationsResponse) => { const encrypted = new EncString(r.uri); - const uri = await this.encryptService.decryptToUtf8(encrypted, key); + const uri = await this.encryptService.decryptString(encrypted, key); return { id: r.id, organizationId: r.organizationId, uri: uri }; }); return forkJoin(results); @@ -164,7 +164,7 @@ export class CriticalAppsService { newEntries: string[], ): Promise { const criticalAppsPromises = newEntries.map(async (url) => { - const encryptedUrlName = await this.encryptService.encrypt(url, key); + const encryptedUrlName = await this.encryptService.encryptString(url, key); return { organizationId: orgId, url: encryptedUrlName?.encryptedString?.toString() ?? "", diff --git a/bitwarden_license/bit-web/src/app/billing/providers/setup/setup-business-unit.component.ts b/bitwarden_license/bit-web/src/app/billing/providers/setup/setup-business-unit.component.ts index 4c8d483a0c5..2f531e1115b 100644 --- a/bitwarden_license/bit-web/src/app/billing/providers/setup/setup-business-unit.component.ts +++ b/bitwarden_license/bit-web/src/app/billing/providers/setup/setup-business-unit.component.ts @@ -84,8 +84,8 @@ export class SetupBusinessUnitComponent extends BaseAcceptComponent { const organizationKey = await firstValueFrom(organizationKey$); - const { encryptedString: encryptedOrganizationKey } = await this.encryptService.encrypt( - organizationKey.key, + const { encryptedString: encryptedOrganizationKey } = await this.encryptService.wrapSymmetricKey( + organizationKey, providerKey, ); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts index 8c9f894f8f6..82e2809dfc8 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts @@ -108,7 +108,7 @@ export class ProjectService { projectView.revisionDate = projectResponse.revisionDate; projectView.read = projectResponse.read; projectView.write = projectResponse.write; - projectView.name = await this.encryptService.decryptToUtf8( + projectView.name = await this.encryptService.decryptString( new EncString(projectResponse.name), orgKey, ); @@ -127,7 +127,7 @@ export class ProjectService { projectListView.organizationId = s.organizationId; projectListView.read = s.read; projectListView.write = s.write; - projectListView.name = await this.encryptService.decryptToUtf8( + projectListView.name = await this.encryptService.decryptString( new EncString(s.name), orgKey, ); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts index c761d73d4a1..113bf130cb5 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts @@ -24,10 +24,10 @@ describe("SecretService", () => { sut = new SecretService(keyService, apiService, encryptService, accessPolicyService); - encryptService.encrypt.mockResolvedValue({ + encryptService.encryptString.mockResolvedValue({ encryptedString: "mockEncryptedString", } as EncString); - encryptService.decryptToUtf8.mockResolvedValue(mockUnencryptedData); + encryptService.decryptString.mockResolvedValue(mockUnencryptedData); }); it("instantiates", () => { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts index 51c49d79f2d..888bf44c410 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts @@ -193,9 +193,9 @@ export class SecretService { secretView.revisionDate = secretResponse.revisionDate; const [name, value, note] = await Promise.all([ - this.encryptService.decryptToUtf8(new EncString(secretResponse.name), orgKey), - this.encryptService.decryptToUtf8(new EncString(secretResponse.value), orgKey), - this.encryptService.decryptToUtf8(new EncString(secretResponse.note), orgKey), + this.encryptService.decryptString(new EncString(secretResponse.name), orgKey), + this.encryptService.decryptString(new EncString(secretResponse.value), orgKey), + this.encryptService.decryptString(new EncString(secretResponse.note), orgKey), ]); secretView.name = name; secretView.value = value; @@ -230,7 +230,7 @@ export class SecretService { const secretListView = new SecretListView(); secretListView.id = s.id; secretListView.organizationId = s.organizationId; - secretListView.name = await this.encryptService.decryptToUtf8( + secretListView.name = await this.encryptService.decryptString( new EncString(s.name), orgKey, ); @@ -259,7 +259,7 @@ export class SecretService { const projectsMappedToSecretView = new SecretProjectView(); projectsMappedToSecretView.id = s.id; projectsMappedToSecretView.name = s.name - ? await this.encryptService.decryptToUtf8(new EncString(s.name), orgKey) + ? await this.encryptService.decryptString(new EncString(s.name), orgKey) : null; return projectsMappedToSecretView; }), diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts index 773cb83e70a..b0df36644d1 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts @@ -130,7 +130,7 @@ export class AccessService { accessTokenResponses.map(async (s) => { const view = new AccessTokenView(); view.id = s.id; - view.name = await this.encryptService.decryptToUtf8(new EncString(s.name), orgKey); + view.name = await this.encryptService.decryptString(new EncString(s.name), orgKey); view.scopes = s.scopes; view.expireAt = s.expireAt ? new Date(s.expireAt) : null; view.creationDate = new Date(s.creationDate); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts index a56111bc655..082d2de066a 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts @@ -144,7 +144,7 @@ export class ServiceAccountService { serviceAccountView.creationDate = serviceAccountResponse.creationDate; serviceAccountView.revisionDate = serviceAccountResponse.revisionDate; serviceAccountView.name = serviceAccountResponse.name - ? await this.encryptService.decryptToUtf8( + ? await this.encryptService.decryptString( new EncString(serviceAccountResponse.name), organizationKey, ) @@ -163,7 +163,7 @@ export class ServiceAccountService { view.revisionDate = response.revisionDate; view.accessToSecrets = response.accessToSecrets; view.name = response.name - ? await this.encryptService.decryptToUtf8(new EncString(response.name), organizationKey) + ? await this.encryptService.decryptString(new EncString(response.name), organizationKey) : null; return view; } diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts index 6b527d56502..6f9f0727ddc 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts @@ -28,8 +28,8 @@ describe("SecretsManagerPortingApiService", () => { sut = new SecretsManagerPortingApiService(apiService, encryptService, keyService); - encryptService.encrypt.mockResolvedValue(mockEncryptedString); - encryptService.decryptToUtf8.mockResolvedValue(mockUnencryptedString); + encryptService.encryptString.mockResolvedValue(mockEncryptedString); + encryptService.decryptString.mockResolvedValue(mockUnencryptedString); const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts index c9d63e61400..279c610ea6c 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts @@ -129,7 +129,7 @@ export class SecretsManagerPortingApiService { exportData.projects.map(async (p) => { const project = new SecretsManagerExportProject(); project.id = p.id; - project.name = await this.encryptService.decryptToUtf8(new EncString(p.name), orgKey); + project.name = await this.encryptService.decryptString(new EncString(p.name), orgKey); return project; }), ); @@ -139,9 +139,9 @@ export class SecretsManagerPortingApiService { const secret = new SecretsManagerExportSecret(); [secret.key, secret.value, secret.note] = await Promise.all([ - this.encryptService.decryptToUtf8(new EncString(s.key), orgKey), - this.encryptService.decryptToUtf8(new EncString(s.value), orgKey), - this.encryptService.decryptToUtf8(new EncString(s.note), orgKey), + this.encryptService.decryptString(new EncString(s.key), orgKey), + this.encryptService.decryptString(new EncString(s.value), orgKey), + this.encryptService.decryptString(new EncString(s.note), orgKey), ]); secret.id = s.id; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts index d6bc807686a..51231184d77 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts @@ -138,7 +138,7 @@ describe("AccessPolicyService", () => { const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; keyService.getOrgKey.mockResolvedValue(mockOrgKey); - encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c.encryptedString)); + encryptService.decryptString.mockImplementation((c) => Promise.resolve(c.encryptedString)); const organizationId = Utils.newGuid(); const serviceAccountId = Utils.newGuid(); @@ -175,7 +175,7 @@ describe("AccessPolicyService", () => { const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; keyService.getOrgKey.mockResolvedValue(mockOrgKey); - encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c.encryptedString)); + encryptService.decryptString.mockImplementation((c) => Promise.resolve(c.encryptedString)); const organizationId = Utils.newGuid(); const projectId = Utils.newGuid(); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts index 5223135c17a..6fc8da05036 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts @@ -350,7 +350,7 @@ export class AccessPolicyService { ...this.createBaseAccessPolicyView(response), grantedProjectId: response.grantedProjectId, grantedProjectName: response.grantedProjectName - ? await this.encryptService.decryptToUtf8( + ? await this.encryptService.decryptString( new EncString(response.grantedProjectName), organizationKey, ) @@ -394,7 +394,7 @@ export class AccessPolicyService { ...this.createBaseAccessPolicyView(response), serviceAccountId: response.serviceAccountId, serviceAccountName: response.serviceAccountName - ? await this.encryptService.decryptToUtf8( + ? await this.encryptService.decryptString( new EncString(response.serviceAccountName), orgKey, ) @@ -420,7 +420,7 @@ export class AccessPolicyService { if (r.type === "serviceAccount" || r.type === "project") { view.name = r.name - ? await this.encryptService.decryptToUtf8(new EncString(r.name), orgKey) + ? await this.encryptService.decryptString(new EncString(r.name), orgKey) : null; } else { view.name = r.name; diff --git a/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts b/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts index 890353d9039..293090ce315 100644 --- a/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts +++ b/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts @@ -116,7 +116,7 @@ export class DefaultCollectionAdminService implements CollectionAdminService { const promises = collections.map(async (c) => { const view = new CollectionAdminView(); view.id = c.id; - view.name = await this.encryptService.decryptToUtf8(new EncString(c.name), orgKey); + view.name = await this.encryptService.decryptString(new EncString(c.name), orgKey); view.externalId = c.externalId; view.organizationId = c.organizationId; @@ -146,7 +146,7 @@ export class DefaultCollectionAdminService implements CollectionAdminService { } const collection = new CollectionRequest(); collection.externalId = model.externalId; - collection.name = (await this.encryptService.encrypt(model.name, key)).encryptedString; + collection.name = (await this.encryptService.encryptString(model.name, key)).encryptedString; collection.groups = model.groups.map( (group) => new SelectionReadOnlyRequest(group.id, group.readOnly, group.hidePasswords, group.manage), diff --git a/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts b/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts index 7fe81ade4d2..11a114dc04e 100644 --- a/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts +++ b/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts @@ -120,7 +120,7 @@ const mockStateProvider = () => { const mockCryptoService = () => { const keyService = mock(); const encryptService = mock(); - encryptService.decryptToUtf8 + encryptService.decryptString .calledWith(expect.any(EncString), expect.anything()) .mockResolvedValue("DECRYPTED_STRING"); diff --git a/libs/admin-console/src/common/collections/services/default-collection.service.ts b/libs/admin-console/src/common/collections/services/default-collection.service.ts index 1ae58d3eef3..a1dd0419e2c 100644 --- a/libs/admin-console/src/common/collections/services/default-collection.service.ts +++ b/libs/admin-console/src/common/collections/services/default-collection.service.ts @@ -113,7 +113,7 @@ export class DefaultCollectionService implements CollectionService { collection.organizationId = model.organizationId; collection.readOnly = model.readOnly; collection.externalId = model.externalId; - collection.name = await this.encryptService.encrypt(model.name, key); + collection.name = await this.encryptService.encryptString(model.name, key); return collection; } diff --git a/libs/admin-console/src/common/collections/services/default-vnext-collection.service.spec.ts b/libs/admin-console/src/common/collections/services/default-vnext-collection.service.spec.ts index 9700fcb695a..07330bad00d 100644 --- a/libs/admin-console/src/common/collections/services/default-vnext-collection.service.spec.ts +++ b/libs/admin-console/src/common/collections/services/default-vnext-collection.service.spec.ts @@ -46,8 +46,8 @@ describe("DefaultvNextCollectionService", () => { keyService.orgKeys$.mockReturnValue(cryptoKeys); // Set up mock decryption - encryptService.decryptToUtf8 - .calledWith(expect.any(EncString), expect.any(SymmetricCryptoKey), expect.any(String)) + encryptService.decryptString + .calledWith(expect.any(EncString), expect.any(SymmetricCryptoKey)) .mockImplementation((encString, key) => Promise.resolve(encString.data.replace("ENC_", "DEC_")), ); @@ -103,12 +103,12 @@ describe("DefaultvNextCollectionService", () => { ]); // Assert that the correct org keys were used for each encrypted string - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith( + expect(encryptService.decryptString).toHaveBeenCalledWith( expect.objectContaining(new EncString(collection1.name)), orgKey1, expect.any(String), ); - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith( + expect(encryptService.decryptString).toHaveBeenCalledWith( expect.objectContaining(new EncString(collection2.name)), orgKey2, expect.any(String), diff --git a/libs/admin-console/src/common/collections/services/default-vnext-collection.service.ts b/libs/admin-console/src/common/collections/services/default-vnext-collection.service.ts index 0ef8ae99ab3..4dcda795afe 100644 --- a/libs/admin-console/src/common/collections/services/default-vnext-collection.service.ts +++ b/libs/admin-console/src/common/collections/services/default-vnext-collection.service.ts @@ -113,7 +113,7 @@ export class DefaultvNextCollectionService implements vNextCollectionService { collection.organizationId = model.organizationId; collection.readOnly = model.readOnly; collection.externalId = model.externalId; - collection.name = await this.encryptService.encrypt(model.name, key); + collection.name = await this.encryptService.encryptString(model.name, key); return collection; } diff --git a/libs/angular/src/vault/components/attachments.component.ts b/libs/angular/src/vault/components/attachments.component.ts index b1bfcde852a..49c1caf2abc 100644 --- a/libs/angular/src/vault/components/attachments.component.ts +++ b/libs/angular/src/vault/components/attachments.component.ts @@ -202,7 +202,7 @@ export class AttachmentsComponent implements OnInit { attachment.key != null ? attachment.key : await this.keyService.getOrgKey(this.cipher.organizationId); - const decBuf = await this.encryptService.decryptToBytes(encBuf, key); + const decBuf = await this.encryptService.decryptFileData(encBuf, key); this.fileDownloadService.download({ fileName: attachment.fileName, blobData: decBuf, @@ -281,7 +281,7 @@ export class AttachmentsComponent implements OnInit { attachment.key != null ? attachment.key : await this.keyService.getOrgKey(this.cipher.organizationId); - const decBuf = await this.encryptService.decryptToBytes(encBuf, key); + const decBuf = await this.encryptService.decryptFileData(encBuf, key); const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(getUserId), ); diff --git a/libs/angular/src/vault/components/view.component.ts b/libs/angular/src/vault/components/view.component.ts index 6b6f24f4217..9d5a8fe9e62 100644 --- a/libs/angular/src/vault/components/view.component.ts +++ b/libs/angular/src/vault/components/view.component.ts @@ -463,7 +463,7 @@ export class ViewComponent implements OnDestroy, OnInit { attachment.key != null ? attachment.key : await this.keyService.getOrgKey(this.cipher.organizationId); - const decBuf = await this.encryptService.decryptToBytes(encBuf, key); + const decBuf = await this.encryptService.decryptFileData(encBuf, key); this.fileDownloadService.download({ fileName: attachment.fileName, blobData: decBuf, diff --git a/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts index 2cdeb710ab9..ebbe2f3b6cb 100644 --- a/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts @@ -230,7 +230,7 @@ describe("WebAuthnLoginStrategy", () => { const mockUserKeyArray: Uint8Array = randomBytes(32); const mockUserKey = new SymmetricCryptoKey(mockUserKeyArray) as UserKey; - encryptService.decryptToBytes.mockResolvedValue(mockPrfPrivateKey); + encryptService.unwrapDecapsulationKey.mockResolvedValue(mockPrfPrivateKey); encryptService.decapsulateKeyUnsigned.mockResolvedValue( new SymmetricCryptoKey(mockUserKeyArray), ); @@ -246,8 +246,8 @@ describe("WebAuthnLoginStrategy", () => { userId, ); - expect(encryptService.decryptToBytes).toHaveBeenCalledTimes(1); - expect(encryptService.decryptToBytes).toHaveBeenCalledWith( + expect(encryptService.unwrapDecapsulationKey).toHaveBeenCalledTimes(1); + expect(encryptService.unwrapDecapsulationKey).toHaveBeenCalledWith( idTokenResponse.userDecryptionOptions.webAuthnPrfOption.encryptedPrivateKey, webAuthnCredentials.prfKey, ); @@ -279,7 +279,7 @@ describe("WebAuthnLoginStrategy", () => { await webAuthnLoginStrategy.logIn(webAuthnCredentials); // Assert - expect(encryptService.decryptToBytes).not.toHaveBeenCalled(); + expect(encryptService.unwrapDecapsulationKey).not.toHaveBeenCalled(); expect(encryptService.decapsulateKeyUnsigned).not.toHaveBeenCalled(); expect(keyService.setUserKey).not.toHaveBeenCalled(); }); @@ -314,7 +314,7 @@ describe("WebAuthnLoginStrategy", () => { apiService.postIdentityToken.mockResolvedValue(idTokenResponse); - encryptService.decryptToBytes.mockResolvedValue(null); + encryptService.unwrapDecapsulationKey.mockResolvedValue(null); // Act await webAuthnLoginStrategy.logIn(webAuthnCredentials); diff --git a/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts b/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts index 895617b3237..182d44195c7 100644 --- a/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts @@ -82,7 +82,7 @@ export class WebAuthnLoginStrategy extends LoginStrategy { } // decrypt prf encrypted private key - const privateKey = await this.encryptService.decryptToBytes( + const privateKey = await this.encryptService.unwrapDecapsulationKey( webAuthnPrfOption.encryptedPrivateKey, credentials.prfKey, ); diff --git a/libs/auth/src/common/services/pin/pin.service.implementation.ts b/libs/auth/src/common/services/pin/pin.service.implementation.ts index c0034020de8..e884872e178 100644 --- a/libs/auth/src/common/services/pin/pin.service.implementation.ts +++ b/libs/auth/src/common/services/pin/pin.service.implementation.ts @@ -221,7 +221,7 @@ export class PinService implements PinServiceAbstraction { throw new Error("No UserKey provided. Cannot create userKeyEncryptedPin."); } - return await this.encryptService.encrypt(pin, userKey); + return await this.encryptService.encryptString(pin, userKey); } async makePinKey(pin: string, salt: string, kdfConfig: KdfConfig): Promise { @@ -339,9 +339,9 @@ export class PinService implements PinServiceAbstraction { } const pinKey = await this.makePinKey(pin, salt, kdfConfig); - const userKey = await this.encryptService.decryptToBytes(pinKeyEncryptedUserKey, pinKey); + const userKey = await this.encryptService.unwrapSymmetricKey(pinKeyEncryptedUserKey, pinKey); - return new SymmetricCryptoKey(userKey) as UserKey; + return userKey as UserKey; } /** @@ -377,7 +377,7 @@ export class PinService implements PinServiceAbstraction { this.validateUserId(userId, "Cannot validate PIN."); const userKeyEncryptedPin = await this.getUserKeyEncryptedPin(userId); - const decryptedPin = await this.encryptService.decryptToUtf8(userKeyEncryptedPin, userKey); + const decryptedPin = await this.encryptService.decryptString(userKeyEncryptedPin, userKey); const isPinValid = this.cryptoFunctionService.compareFast(decryptedPin, pin); return isPinValid; diff --git a/libs/auth/src/common/services/pin/pin.service.spec.ts b/libs/auth/src/common/services/pin/pin.service.spec.ts index fd33f5d2077..33640e0f9f3 100644 --- a/libs/auth/src/common/services/pin/pin.service.spec.ts +++ b/libs/auth/src/common/services/pin/pin.service.spec.ts @@ -259,11 +259,11 @@ describe("PinService", () => { }); it("should create a userKeyEncryptedPin from the provided PIN and userKey", async () => { - encryptService.encrypt.mockResolvedValue(mockUserKeyEncryptedPin); + encryptService.encryptString.mockResolvedValue(mockUserKeyEncryptedPin); const result = await sut.createUserKeyEncryptedPin(mockPin, mockUserKey); - expect(encryptService.encrypt).toHaveBeenCalledWith(mockPin, mockUserKey); + expect(encryptService.encryptString).toHaveBeenCalledWith(mockPin, mockUserKey); expect(result).toEqual(mockUserKeyEncryptedPin); }); }); @@ -425,7 +425,7 @@ describe("PinService", () => { mockDecryptUserKeyFn(); sut.getUserKeyEncryptedPin = jest.fn().mockResolvedValue(mockUserKeyEncryptedPin); - encryptService.decryptToUtf8.mockResolvedValue(mockPin); + encryptService.decryptString.mockResolvedValue(mockPin); cryptoFunctionService.compareFast.calledWith(mockPin, "1234").mockResolvedValue(true); } @@ -434,7 +434,7 @@ describe("PinService", () => { .fn() .mockResolvedValue(pinKeyEncryptedUserKeyPersistant); sut.makePinKey = jest.fn().mockResolvedValue(mockPinKey); - encryptService.decryptToBytes.mockResolvedValue(mockUserKey.key); + encryptService.unwrapSymmetricKey.mockResolvedValue(mockUserKey); } function mockPinEncryptedKeyDataByPinLockType(pinLockType: PinLockType) { @@ -490,7 +490,7 @@ describe("PinService", () => { it(`should return null when PIN doesn't match after successful user key decryption`, async () => { // Arrange await setupDecryptUserKeyWithPinMocks(pinLockType); - encryptService.decryptToUtf8.mockResolvedValue("9999"); // non matching PIN + encryptService.decryptString.mockResolvedValue("9999"); // non matching PIN // Act const result = await sut.decryptUserKeyWithPin(mockPin, mockUserId); diff --git a/libs/common/src/admin-console/models/domain/encrypted-organization-key.ts b/libs/common/src/admin-console/models/domain/encrypted-organization-key.ts index 984d80ba519..297bcf08d8c 100644 --- a/libs/common/src/admin-console/models/domain/encrypted-organization-key.ts +++ b/libs/common/src/admin-console/models/domain/encrypted-organization-key.ts @@ -56,14 +56,14 @@ export class ProviderEncryptedOrganizationKey implements BaseEncryptedOrganizati ) {} async decrypt(encryptService: EncryptService, providerKeys: Record) { - const decValue = await encryptService.decryptToBytes( + const decValue = await encryptService.unwrapSymmetricKey( new EncString(this.key), providerKeys[this.providerId], ); if (decValue == null) { throw new Error("Failed to decrypt organization key"); } - return new SymmetricCryptoKey(decValue) as OrgKey; + return decValue as OrgKey; } get encryptedOrganizationKey() { diff --git a/libs/common/src/auth/services/token.service.spec.ts b/libs/common/src/auth/services/token.service.spec.ts index 449f5d17ad1..a56853c479c 100644 --- a/libs/common/src/auth/services/token.service.spec.ts +++ b/libs/common/src/auth/services/token.service.spec.ts @@ -293,7 +293,7 @@ describe("TokenService", () => { const mockEncryptedAccessToken = "encryptedAccessToken"; - encryptService.encrypt.mockResolvedValue({ + encryptService.encryptString.mockResolvedValue({ encryptedString: mockEncryptedAccessToken, } as any); @@ -504,7 +504,7 @@ describe("TokenService", () => { .nextState("encryptedAccessToken"); secureStorageService.get.mockResolvedValue(accessTokenKeyB64); - encryptService.decryptToUtf8.mockResolvedValue("decryptedAccessToken"); + encryptService.decryptString.mockResolvedValue("decryptedAccessToken"); // Need to have global active id set to the user id if (!userId) { @@ -1515,7 +1515,7 @@ describe("TokenService", () => { .nextState(encryptedAccessToken); secureStorageService.get.mockResolvedValue(accessTokenKeyB64); - encryptService.decryptToUtf8.mockRejectedValue(new Error("Decryption error")); + encryptService.decryptString.mockRejectedValue(new Error("Decryption error")); // Act const result = await tokenService.getAccessToken(userIdFromAccessToken); diff --git a/libs/common/src/auth/services/token.service.ts b/libs/common/src/auth/services/token.service.ts index 7b87e55cfc7..c27afa6805a 100644 --- a/libs/common/src/auth/services/token.service.ts +++ b/libs/common/src/auth/services/token.service.ts @@ -289,7 +289,7 @@ export class TokenService implements TokenServiceAbstraction { private async encryptAccessToken(accessToken: string, userId: UserId): Promise { const accessTokenKey = await this.getOrCreateAccessTokenKey(userId); - return await this.encryptService.encrypt(accessToken, accessTokenKey); + return await this.encryptService.encryptString(accessToken, accessTokenKey); } private async decryptAccessToken( @@ -302,7 +302,7 @@ export class TokenService implements TokenServiceAbstraction { ); } - const decryptedAccessToken = await this.encryptService.decryptToUtf8( + const decryptedAccessToken = await this.encryptService.decryptString( encryptedAccessToken, accessTokenKey, ); diff --git a/libs/common/src/billing/services/organization-billing.service.ts b/libs/common/src/billing/services/organization-billing.service.ts index 6622cdcdce3..c6bd88d8dd6 100644 --- a/libs/common/src/billing/services/organization-billing.service.ts +++ b/libs/common/src/billing/services/organization-billing.service.ts @@ -120,7 +120,7 @@ export class OrganizationBillingService implements OrganizationBillingServiceAbs private async makeOrganizationKeys(): Promise { const [encryptedKey, key] = await this.keyService.makeOrgKey(); const [publicKey, encryptedPrivateKey] = await this.keyService.makeKeyPair(key); - const encryptedCollectionName = await this.encryptService.encrypt( + const encryptedCollectionName = await this.encryptService.encryptString( this.i18nService.t("defaultCollection"), key, ); diff --git a/libs/common/src/key-management/device-trust/services/device-trust.service.implementation.ts b/libs/common/src/key-management/device-trust/services/device-trust.service.implementation.ts index 205f332d0f9..ff5354b42ab 100644 --- a/libs/common/src/key-management/device-trust/services/device-trust.service.implementation.ts +++ b/libs/common/src/key-management/device-trust/services/device-trust.service.implementation.ts @@ -209,7 +209,7 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { devices.data .filter((device) => device.isTrusted) .map(async (device) => { - const publicKey = await this.encryptService.decryptToBytes( + const publicKey = await this.encryptService.unwrapEncapsulationKey( new EncString(device.encryptedPublicKey), oldUserKey, ); @@ -220,9 +220,9 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { return null; } - const newEncryptedPublicKey = await this.encryptService.encrypt(publicKey, newUserKey); - const newEncryptedUserKey = await this.encryptService.rsaEncrypt( - newUserKey.key, + const newEncryptedPublicKey = await this.encryptService.wrapEncapsulationKey(publicKey, newUserKey); + const newEncryptedUserKey = await this.encryptService.encapsulateKeyUnsigned( + newUserKey, publicKey, ); @@ -278,7 +278,7 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { const currentDeviceKeys = await this.devicesApiService.getDeviceKeys(deviceIdentifier); // Decrypt the existing device public key with the old user key - const decryptedDevicePublicKey = await this.encryptService.decryptToBytes( + const decryptedDevicePublicKey = await this.encryptService.unwrapEncapsulationKey( currentDeviceKeys.encryptedPublicKey, oldUserKey, ); @@ -394,7 +394,7 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { try { // attempt to decrypt encryptedDevicePrivateKey with device key - const devicePrivateKey = await this.encryptService.decryptToBytes( + const devicePrivateKey = await this.encryptService.unwrapDecapsulationKey( encryptedDevicePrivateKey, deviceKey, ); diff --git a/libs/common/src/key-management/device-trust/services/device-trust.service.spec.ts b/libs/common/src/key-management/device-trust/services/device-trust.service.spec.ts index e78fc01b694..c206af0f944 100644 --- a/libs/common/src/key-management/device-trust/services/device-trust.service.spec.ts +++ b/libs/common/src/key-management/device-trust/services/device-trust.service.spec.ts @@ -623,9 +623,9 @@ describe("deviceTrustService", () => { }); it("successfully returns the user key when provided keys (including device key) can decrypt it", async () => { - const decryptToBytesSpy = jest - .spyOn(encryptService, "decryptToBytes") - .mockResolvedValue(new Uint8Array(userKeyBytesLength)); + const unwrapDecapsulationKeySpy = jest + .spyOn(encryptService, "unwrapDecapsulationKey") + .mockResolvedValue(new Uint8Array(2048)); const rsaDecryptSpy = jest .spyOn(encryptService, "decapsulateKeyUnsigned") .mockResolvedValue(new SymmetricCryptoKey(new Uint8Array(userKeyBytesLength))); @@ -638,13 +638,13 @@ describe("deviceTrustService", () => { ); expect(result).toEqual(mockUserKey); - expect(decryptToBytesSpy).toHaveBeenCalledTimes(1); + expect(unwrapDecapsulationKeySpy).toHaveBeenCalledTimes(1); expect(rsaDecryptSpy).toHaveBeenCalledTimes(1); }); it("returns null and removes device key when the decryption fails", async () => { - const decryptToBytesSpy = jest - .spyOn(encryptService, "decryptToBytes") + const unwrapDecapsulationKeySpy = jest + .spyOn(encryptService, "unwrapDecapsulationKey") .mockRejectedValue(new Error("Decryption error")); const setDeviceKeySpy = jest.spyOn(deviceTrustService as any, "setDeviceKey"); @@ -656,7 +656,7 @@ describe("deviceTrustService", () => { ); expect(result).toBeNull(); - expect(decryptToBytesSpy).toHaveBeenCalledTimes(1); + expect(unwrapDecapsulationKeySpy).toHaveBeenCalledTimes(1); expect(setDeviceKeySpy).toHaveBeenCalledTimes(1); expect(setDeviceKeySpy).toHaveBeenCalledWith(mockUserId, null); }); @@ -704,9 +704,9 @@ describe("deviceTrustService", () => { DeviceResponse, ), ); - encryptService.decryptToBytes.mockResolvedValue(null); - encryptService.encrypt.mockResolvedValue(new EncString("test_encrypted_data")); - encryptService.rsaEncrypt.mockResolvedValue(new EncString("test_encrypted_data")); + encryptService.decryptBytes.mockResolvedValue(null); + encryptService.encryptString.mockResolvedValue(new EncString("test_encrypted_data")); + encryptService.encapsulateKeyUnsigned.mockResolvedValue(new EncString("test_encrypted_data")); const protectedDeviceResponse = new ProtectedDeviceResponse({ id: "id", @@ -750,9 +750,9 @@ describe("deviceTrustService", () => { DeviceResponse, ), ); - encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(64)); - encryptService.encrypt.mockResolvedValue(new EncString("test_encrypted_data")); - encryptService.rsaEncrypt.mockResolvedValue(new EncString("test_encrypted_data")); + encryptService.unwrapEncapsulationKey.mockResolvedValue(new Uint8Array(64)); + encryptService.wrapEncapsulationKey.mockResolvedValue(new EncString("test_encrypted_data")); + encryptService.encapsulateKeyUnsigned.mockResolvedValue(new EncString("test_encrypted_data")); const protectedDeviceResponse = new ProtectedDeviceResponse({ id: "", @@ -860,7 +860,7 @@ describe("deviceTrustService", () => { }); // Mock the decryption of the public key with the old user key - encryptService.decryptToBytes.mockImplementationOnce((_encValue, privateKeyValue) => { + encryptService.unwrapEncapsulationKey.mockImplementationOnce((_encValue, privateKeyValue) => { expect(privateKeyValue.key.byteLength).toBe(64); expect(new Uint8Array(privateKeyValue.key)[0]).toBe(FakeOldUserKeyMarker); const data = new Uint8Array(250); diff --git a/libs/common/src/key-management/master-password/services/master-password.service.ts b/libs/common/src/key-management/master-password/services/master-password.service.ts index 9ed01cf0c83..0c3486fb665 100644 --- a/libs/common/src/key-management/master-password/services/master-password.service.ts +++ b/libs/common/src/key-management/master-password/services/master-password.service.ts @@ -163,20 +163,18 @@ export class MasterPasswordService implements InternalMasterPasswordServiceAbstr throw new Error("No master key found."); } - let decUserKey: Uint8Array; + let decUserKey: SymmetricCryptoKey; if (userKey.encryptionType === EncryptionType.AesCbc256_B64) { - decUserKey = await this.encryptService.decryptToBytes( + decUserKey = await this.encryptService.unwrapSymmetricKey( userKey, masterKey, - "Content: User Key; Encrypting Key: Master Key", ); } else if (userKey.encryptionType === EncryptionType.AesCbc256_HmacSha256_B64) { const newKey = await this.keyGenerationService.stretchKey(masterKey); - decUserKey = await this.encryptService.decryptToBytes( + decUserKey = await this.encryptService.unwrapSymmetricKey( userKey, newKey, - "Content: User Key; Encrypting Key: Stretched Master Key", ); } else { throw new Error("Unsupported encryption type."); @@ -187,6 +185,6 @@ export class MasterPasswordService implements InternalMasterPasswordServiceAbstr return null; } - return new SymmetricCryptoKey(decUserKey) as UserKey; + return decUserKey as UserKey; } } diff --git a/libs/common/src/platform/models/domain/domain-base.spec.ts b/libs/common/src/platform/models/domain/domain-base.spec.ts index 0c13f9a2119..66dfce6fd71 100644 --- a/libs/common/src/platform/models/domain/domain-base.spec.ts +++ b/libs/common/src/platform/models/domain/domain-base.spec.ts @@ -2,7 +2,6 @@ import { mock, MockProxy } from "jest-mock-extended"; import { makeEncString, makeSymmetricCryptoKey } from "../../../../spec"; import { EncryptService } from "../../../key-management/crypto/abstractions/encrypt.service"; -import { Utils } from "../../misc/utils"; import Domain from "./domain-base"; import { EncString } from "./enc-string"; @@ -22,24 +21,11 @@ describe("DomainBase", () => { }); function setUpCryptography() { - encryptService.encrypt.mockImplementation((value) => { - let data: string; - if (typeof value === "string") { - data = value; - } else { - data = Utils.fromBufferToUtf8(value); - } + encryptService.encryptString.mockImplementation((value) => Promise.resolve(makeEncString(value))); - return Promise.resolve(makeEncString(data)); - }); - - encryptService.decryptToUtf8.mockImplementation((value) => { + encryptService.decryptString.mockImplementation((value) => { return Promise.resolve(value.data); }); - - encryptService.decryptToBytes.mockImplementation((value) => { - return Promise.resolve(value.dataBytes); - }); } describe("decryptWithKey", () => { @@ -82,7 +68,7 @@ describe("DomainBase", () => { const domain = new TestDomain(); - domain.encToString = await encryptService.encrypt("string", key); + domain.encToString = await encryptService.encryptString("string", key); const decrypted = await domain["decryptObjWithKey"](["encToString"], key, encryptService); @@ -96,8 +82,8 @@ describe("DomainBase", () => { const domain = new TestDomain(); - domain.encToString = await encryptService.encrypt("string", key); - domain.encString2 = await encryptService.encrypt("string2", key); + domain.encToString = await encryptService.encryptString("string", key); + domain.encString2 = await encryptService.encryptString("string2", key); const decrypted = await domain["decryptObjWithKey"]( ["encToString", "encString2"], diff --git a/libs/common/src/platform/models/domain/enc-string.spec.ts b/libs/common/src/platform/models/domain/enc-string.spec.ts index c3f257d442a..e144b9ed33f 100644 --- a/libs/common/src/platform/models/domain/enc-string.spec.ts +++ b/libs/common/src/platform/models/domain/enc-string.spec.ts @@ -7,7 +7,6 @@ import { EncryptService } from "../../../key-management/crypto/abstractions/encr import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key"; import { UserKey, OrgKey } from "../../../types/key"; import { EncryptionType } from "../../enums"; -import { Utils } from "../../misc/utils"; import { ContainerService } from "../../services/container.service"; import { EncString } from "./enc-string"; @@ -87,7 +86,7 @@ describe("EncString", () => { ); const encryptService = mock(); - encryptService.decryptToUtf8 + encryptService.decryptString .calledWith(encString, expect.anything()) .mockResolvedValue("decrypted"); @@ -106,7 +105,7 @@ describe("EncString", () => { it("result should be cached", async () => { const decrypted = await encString.decrypt(null); - expect(encryptService.decryptToUtf8).toBeCalledTimes(1); + expect(encryptService.decryptString).toBeCalledTimes(1); expect(decrypted).toBe("decrypted"); }); @@ -118,24 +117,17 @@ describe("EncString", () => { const keyService = mock(); const encryptService = mock(); - encryptService.decryptToUtf8 + encryptService.decryptString .calledWith(encString, expect.anything()) .mockResolvedValue("decrypted"); function setupEncryption() { - encryptService.encrypt.mockImplementation(async (data, key) => { - if (typeof data === "string") { - return makeEncString(data); - } else { - return makeEncString(Utils.fromBufferToUtf8(data)); - } + encryptService.encryptString.mockImplementation(async (data, key) => { + return makeEncString(data); }); - encryptService.decryptToUtf8.mockImplementation(async (encString, key) => { + encryptService.decryptString.mockImplementation(async (encString, key) => { return encString.data; }); - encryptService.decryptToBytes.mockImplementation(async (encString, key) => { - return encString.dataBytes; - }); } beforeEach(() => { @@ -148,7 +140,7 @@ describe("EncString", () => { const key = new SymmetricCryptoKey(makeStaticByteArray(32)); await encString.decryptWithKey(key, encryptService); - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(encString, key, "domain-withkey"); + expect(encryptService.decryptString).toHaveBeenCalledWith(encString, key); }); it("fails to decrypt when key is null", async () => { @@ -169,7 +161,7 @@ describe("EncString", () => { }); it("fails to decrypt when encryptService throws", async () => { - encryptService.decryptToUtf8.mockRejectedValue("error"); + encryptService.decryptString.mockRejectedValue("error"); const decrypted = await encString.decryptWithKey( new SymmetricCryptoKey(makeStaticByteArray(32)), @@ -330,7 +322,7 @@ describe("EncString", () => { }); it("handles value it can't decrypt", async () => { - encryptService.decryptToUtf8.mockRejectedValue("error"); + encryptService.decryptString.mockRejectedValue("error"); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); @@ -350,7 +342,7 @@ describe("EncString", () => { await encString.decrypt(null, key); expect(keyService.getUserKeyWithLegacySupport).not.toHaveBeenCalled(); - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(encString, key, "provided-key"); + expect(encryptService.decryptString).toHaveBeenCalledWith(encString, key); }); it("gets an organization key if required", async () => { @@ -361,10 +353,9 @@ describe("EncString", () => { await encString.decrypt("orgId", null); expect(keyService.getOrgKey).toHaveBeenCalledWith("orgId"); - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith( + expect(encryptService.decryptString).toHaveBeenCalledWith( encString, orgKey, - "domain-orgkey-orgId", ); }); @@ -376,10 +367,9 @@ describe("EncString", () => { await encString.decrypt(null, null); expect(keyService.getUserKeyWithLegacySupport).toHaveBeenCalledWith(); - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith( + expect(encryptService.decryptString).toHaveBeenCalledWith( encString, userKey, - "domain-withlegacysupport-masterkey", ); }); }); diff --git a/libs/common/src/platform/models/domain/enc-string.ts b/libs/common/src/platform/models/domain/enc-string.ts index b0b03e0fb3c..61b9c6a30e8 100644 --- a/libs/common/src/platform/models/domain/enc-string.ts +++ b/libs/common/src/platform/models/domain/enc-string.ts @@ -163,30 +163,18 @@ export class EncString implements Encrypted { return this.decryptedValue; } - let decryptTrace = "provided-key"; try { if (key == null) { key = await this.getKeyForDecryption(orgId); - decryptTrace = orgId == null ? `domain-orgkey-${orgId}` : "domain-userkey|masterkey"; - if (orgId != null) { - decryptTrace = `domain-orgkey-${orgId}`; - } else { - const cryptoService = Utils.getContainerService().getKeyService(); - decryptTrace = - (await cryptoService.getUserKey()) == null - ? "domain-withlegacysupport-masterkey" - : "domain-withlegacysupport-userkey"; - } } if (key == null) { throw new Error("No key to decrypt EncString with orgId " + orgId); } const encryptService = Utils.getContainerService().getEncryptService(); - this.decryptedValue = await encryptService.decryptToUtf8( + this.decryptedValue = await encryptService.decryptString( this, key, - decryptTrace == null ? context : `${decryptTrace}${context || ""}`, ); // FIXME: Remove when updating file. Eslint update // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -206,7 +194,7 @@ export class EncString implements Encrypted { throw new Error("No key to decrypt EncString"); } - this.decryptedValue = await encryptService.decryptToUtf8(this, key, decryptTrace); + this.decryptedValue = await encryptService.decryptString(this, key); // FIXME: Remove when updating file. Eslint update // eslint-disable-next-line @typescript-eslint/no-unused-vars } catch (e) { diff --git a/libs/common/src/tools/cryptography/organization-key-encryptor.spec.ts b/libs/common/src/tools/cryptography/organization-key-encryptor.spec.ts index 3d93db81389..440752b999d 100644 --- a/libs/common/src/tools/cryptography/organization-key-encryptor.spec.ts +++ b/libs/common/src/tools/cryptography/organization-key-encryptor.spec.ts @@ -22,8 +22,8 @@ describe("OrgKeyEncryptor", () => { // on this property--that the facade treats its data like a opaque objects--to trace // the data through several function calls. Should the encryptor interact with the // objects themselves, these mocks will break. - encryptService.encrypt.mockImplementation((p) => Promise.resolve(p as unknown as EncString)); - encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c as unknown as string)); + encryptService.encryptString.mockImplementation((p) => Promise.resolve(p as unknown as EncString)); + encryptService.decryptString.mockImplementation((c) => Promise.resolve(c as unknown as string)); dataPacker.pack.mockImplementation((v) => v as string); dataPacker.unpack.mockImplementation((v: string) => v as T); }); @@ -95,7 +95,7 @@ describe("OrgKeyEncryptor", () => { // these are data flow expectations; the operations all all pass-through mocks expect(dataPacker.pack).toHaveBeenCalledWith(value); - expect(encryptService.encrypt).toHaveBeenCalledWith(value, orgKey); + expect(encryptService.encryptString).toHaveBeenCalledWith(value, orgKey); expect(result).toBe(value); }); }); @@ -117,7 +117,7 @@ describe("OrgKeyEncryptor", () => { const result = await encryptor.decrypt(secret); // these are data flow expectations; the operations all all pass-through mocks - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(secret, orgKey); + expect(encryptService.decryptString).toHaveBeenCalledWith(secret, orgKey); expect(dataPacker.unpack).toHaveBeenCalledWith(secret); expect(result).toBe(secret); }); diff --git a/libs/common/src/tools/cryptography/organization-key-encryptor.ts b/libs/common/src/tools/cryptography/organization-key-encryptor.ts index 31f3db91232..99b47c48670 100644 --- a/libs/common/src/tools/cryptography/organization-key-encryptor.ts +++ b/libs/common/src/tools/cryptography/organization-key-encryptor.ts @@ -37,7 +37,7 @@ export class OrganizationKeyEncryptor extends OrganizationEncryptor { this.assertHasValue("secret", secret); let packed = this.dataPacker.pack(secret); - const encrypted = await this.encryptService.encrypt(packed, this.key); + const encrypted = await this.encryptService.encryptString(packed, this.key); packed = null; return encrypted; @@ -46,7 +46,7 @@ export class OrganizationKeyEncryptor extends OrganizationEncryptor { async decrypt(secret: EncString): Promise> { this.assertHasValue("secret", secret); - let decrypted = await this.encryptService.decryptToUtf8(secret, this.key); + let decrypted = await this.encryptService.decryptString(secret, this.key); const unpacked = this.dataPacker.unpack(decrypted); decrypted = null; diff --git a/libs/common/src/tools/cryptography/user-key-encryptor.spec.ts b/libs/common/src/tools/cryptography/user-key-encryptor.spec.ts index e52190500b0..eb869763539 100644 --- a/libs/common/src/tools/cryptography/user-key-encryptor.spec.ts +++ b/libs/common/src/tools/cryptography/user-key-encryptor.spec.ts @@ -22,8 +22,8 @@ describe("UserKeyEncryptor", () => { // on this property--that the facade treats its data like a opaque objects--to trace // the data through several function calls. Should the encryptor interact with the // objects themselves, these mocks will break. - encryptService.encrypt.mockImplementation((p) => Promise.resolve(p as unknown as EncString)); - encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c as unknown as string)); + encryptService.encryptString.mockImplementation((p) => Promise.resolve(p as unknown as EncString)); + encryptService.decryptString.mockImplementation((c) => Promise.resolve(c as unknown as string)); dataPacker.pack.mockImplementation((v) => v as string); dataPacker.unpack.mockImplementation((v: string) => v as T); }); @@ -95,7 +95,7 @@ describe("UserKeyEncryptor", () => { // these are data flow expectations; the operations all all pass-through mocks expect(dataPacker.pack).toHaveBeenCalledWith(value); - expect(encryptService.encrypt).toHaveBeenCalledWith(value, userKey); + expect(encryptService.encryptString).toHaveBeenCalledWith(value, userKey); expect(result).toBe(value); }); }); @@ -117,7 +117,7 @@ describe("UserKeyEncryptor", () => { const result = await encryptor.decrypt(secret); // these are data flow expectations; the operations all all pass-through mocks - expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(secret, userKey); + expect(encryptService.decryptString).toHaveBeenCalledWith(secret, userKey); expect(dataPacker.unpack).toHaveBeenCalledWith(secret); expect(result).toBe(secret); }); diff --git a/libs/common/src/tools/cryptography/user-key-encryptor.ts b/libs/common/src/tools/cryptography/user-key-encryptor.ts index 4b7cd1516a0..74e41f7af6d 100644 --- a/libs/common/src/tools/cryptography/user-key-encryptor.ts +++ b/libs/common/src/tools/cryptography/user-key-encryptor.ts @@ -37,7 +37,7 @@ export class UserKeyEncryptor extends UserEncryptor { this.assertHasValue("secret", secret); let packed = this.dataPacker.pack(secret); - const encrypted = await this.encryptService.encrypt(packed, this.key); + const encrypted = await this.encryptService.encryptString(packed, this.key); packed = null; return encrypted; @@ -46,7 +46,7 @@ export class UserKeyEncryptor extends UserEncryptor { async decrypt(secret: EncString): Promise> { this.assertHasValue("secret", secret); - let decrypted = await this.encryptService.decryptToUtf8(secret, this.key); + let decrypted = await this.encryptService.decryptString(secret, this.key); const unpacked = this.dataPacker.unpack(decrypted); decrypted = null; diff --git a/libs/common/src/tools/send/models/domain/send.spec.ts b/libs/common/src/tools/send/models/domain/send.spec.ts index 79f6c03adc8..7112ad7f751 100644 --- a/libs/common/src/tools/send/models/domain/send.spec.ts +++ b/libs/common/src/tools/send/models/domain/send.spec.ts @@ -112,7 +112,7 @@ describe("Send", () => { const encryptService = mock(); const keyService = mock(); - encryptService.decryptToBytes + encryptService.decryptBytes .calledWith(send.key, userKey) .mockResolvedValue(makeStaticByteArray(32)); keyService.makeSendKey.mockResolvedValue("cryptoKey" as any); diff --git a/libs/common/src/tools/send/models/domain/send.ts b/libs/common/src/tools/send/models/domain/send.ts index f12a0010fab..78d7966bb63 100644 --- a/libs/common/src/tools/send/models/domain/send.ts +++ b/libs/common/src/tools/send/models/domain/send.ts @@ -79,7 +79,8 @@ export class Send extends Domain { try { const sendKeyEncryptionKey = await keyService.getUserKey(); - model.key = await encryptService.decryptToBytes(this.key, sendKeyEncryptionKey); + // model.key is a seed used to derive a key, not a SymmetricCryptoKey + model.key = await encryptService.decryptBytes(this.key, sendKeyEncryptionKey); model.cryptoKey = await keyService.makeSendKey(model.key); // FIXME: Remove when updating file. Eslint update // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/libs/common/src/tools/send/services/send.service.spec.ts b/libs/common/src/tools/send/services/send.service.spec.ts index cd8d52fe373..fadb42553d3 100644 --- a/libs/common/src/tools/send/services/send.service.spec.ts +++ b/libs/common/src/tools/send/services/send.service.spec.ts @@ -477,7 +477,7 @@ describe("SendService", () => { let encryptedKey: EncString; beforeEach(() => { - encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(32)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(new Uint8Array(32))); encryptedKey = new EncString("Re-encrypted Send Key"); encryptService.wrapSymmetricKey.mockResolvedValue(encryptedKey); }); diff --git a/libs/common/src/tools/send/services/send.service.ts b/libs/common/src/tools/send/services/send.service.ts index cefd9942d29..db3834789c8 100644 --- a/libs/common/src/tools/send/services/send.service.ts +++ b/libs/common/src/tools/send/services/send.service.ts @@ -86,12 +86,12 @@ export class SendService implements InternalSendServiceAbstraction { userKey = await this.keyService.getUserKey(); } // Key is not a SymmetricCryptoKey, but key material used to derive the cryptoKey - send.key = await this.encryptService.encrypt(model.key, userKey); - send.name = await this.encryptService.encrypt(model.name, model.cryptoKey); - send.notes = await this.encryptService.encrypt(model.notes, model.cryptoKey); + send.key = await this.encryptService.encryptBytes(model.key, userKey); + send.name = await this.encryptService.encryptString(model.name, model.cryptoKey); + send.notes = await this.encryptService.encryptString(model.notes, model.cryptoKey); if (send.type === SendType.Text) { send.text = new SendText(); - send.text.text = await this.encryptService.encrypt(model.text.text, model.cryptoKey); + send.text.text = await this.encryptService.encryptString(model.text.text, model.cryptoKey); send.text.hidden = model.text.hidden; } else if (send.type === SendType.File) { send.file = new SendFile(); @@ -292,9 +292,7 @@ export class SendService implements InternalSendServiceAbstraction { ) { const requests = await Promise.all( sends.map(async (send) => { - const sendKey = new SymmetricCryptoKey( - await this.encryptService.decryptToBytes(send.key, originalUserKey), - ); + const sendKey = await this.encryptService.unwrapSymmetricKey(send.key, originalUserKey); send.key = await this.encryptService.wrapSymmetricKey(sendKey, rotateUserKey); return new SendWithIdRequest(send); }), @@ -333,8 +331,8 @@ export class SendService implements InternalSendServiceAbstraction { if (key == null) { key = await this.keyService.getUserKey(); } - const encFileName = await this.encryptService.encrypt(fileName, key); - const encFileData = await this.encryptService.encryptToBytes(new Uint8Array(data), key); + const encFileName = await this.encryptService.encryptString(fileName, key); + const encFileData = await this.encryptService.encryptFileData(new Uint8Array(data), key); return [encFileName, encFileData]; } diff --git a/libs/common/src/vault/models/domain/attachment.spec.ts b/libs/common/src/vault/models/domain/attachment.spec.ts index d1ee1dcc1ef..77afff66eed 100644 --- a/libs/common/src/vault/models/domain/attachment.spec.ts +++ b/libs/common/src/vault/models/domain/attachment.spec.ts @@ -77,7 +77,8 @@ describe("Attachment", () => { attachment.key = mockEnc("key"); attachment.fileName = mockEnc("fileName"); - encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(32)); + encryptService.decryptFileData.mockResolvedValue(makeStaticByteArray(32)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64))); const view = await attachment.decrypt(null); @@ -105,7 +106,7 @@ describe("Attachment", () => { await attachment.decrypt(null, "", providedKey); expect(keyService.getUserKeyWithLegacySupport).not.toHaveBeenCalled(); - expect(encryptService.decryptToBytes).toHaveBeenCalledWith(attachment.key, providedKey); + expect(encryptService.unwrapSymmetricKey).toHaveBeenCalledWith(attachment.key, providedKey); }); it("gets an organization key if required", async () => { @@ -115,7 +116,7 @@ describe("Attachment", () => { await attachment.decrypt("orgId", "", null); expect(keyService.getOrgKey).toHaveBeenCalledWith("orgId"); - expect(encryptService.decryptToBytes).toHaveBeenCalledWith(attachment.key, orgKey); + expect(encryptService.unwrapSymmetricKey).toHaveBeenCalledWith(attachment.key, orgKey); }); it("gets the user's decryption key if required", async () => { @@ -125,7 +126,7 @@ describe("Attachment", () => { await attachment.decrypt(null, "", null); expect(keyService.getUserKeyWithLegacySupport).toHaveBeenCalled(); - expect(encryptService.decryptToBytes).toHaveBeenCalledWith(attachment.key, userKey); + expect(encryptService.unwrapSymmetricKey).toHaveBeenCalledWith(attachment.key, userKey); }); }); }); diff --git a/libs/common/src/vault/models/domain/attachment.ts b/libs/common/src/vault/models/domain/attachment.ts index 16f3adbe307..15ce06e0881 100644 --- a/libs/common/src/vault/models/domain/attachment.ts +++ b/libs/common/src/vault/models/domain/attachment.ts @@ -66,8 +66,8 @@ export class Attachment extends Domain { } const encryptService = Utils.getContainerService().getEncryptService(); - const decValue = await encryptService.decryptToBytes(this.key, encKey); - return new SymmetricCryptoKey(decValue); + const decValue = await encryptService.unwrapSymmetricKey(this.key, encKey); + return decValue; // FIXME: Remove when updating file. Eslint update // eslint-disable-next-line @typescript-eslint/no-unused-vars } catch (e) { diff --git a/libs/common/src/vault/models/domain/cipher.spec.ts b/libs/common/src/vault/models/domain/cipher.spec.ts index 1b2b093a553..72134b7accc 100644 --- a/libs/common/src/vault/models/domain/cipher.spec.ts +++ b/libs/common/src/vault/models/domain/cipher.spec.ts @@ -1,6 +1,7 @@ import { mock } from "jest-mock-extended"; import { Jsonify } from "type-fest"; +import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { KeyService } from "@bitwarden/key-management"; import { makeStaticByteArray, mockEnc, mockFromJson } from "../../../../spec/utils"; @@ -246,7 +247,7 @@ describe("Cipher DTO", () => { const encryptService = mock(); const cipherService = mock(); - encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64))); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); @@ -367,7 +368,7 @@ describe("Cipher DTO", () => { const encryptService = mock(); const cipherService = mock(); - encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64))); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); @@ -506,7 +507,7 @@ describe("Cipher DTO", () => { const encryptService = mock(); const cipherService = mock(); - encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64))); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); @@ -669,7 +670,7 @@ describe("Cipher DTO", () => { const encryptService = mock(); const cipherService = mock(); - encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64))); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); diff --git a/libs/common/src/vault/models/domain/cipher.ts b/libs/common/src/vault/models/domain/cipher.ts index f23e3c0c579..3e63673c7b0 100644 --- a/libs/common/src/vault/models/domain/cipher.ts +++ b/libs/common/src/vault/models/domain/cipher.ts @@ -143,17 +143,16 @@ export class Cipher extends Domain implements Decryptable { if (this.key != null) { const encryptService = Utils.getContainerService().getEncryptService(); - const keyBytes = await encryptService.decryptToBytes( + const cipherKey = await encryptService.unwrapSymmetricKey( this.key, encKey, - `Cipher Id: ${this.id}; Content: CipherKey; IsEncryptedByOrgKey: ${this.organizationId != null}`, ); - if (keyBytes == null) { + if (cipherKey == null) { model.name = "[error: cannot decrypt]"; model.decryptionFailure = true; return model; } - encKey = new SymmetricCryptoKey(keyBytes); + encKey = cipherKey; bypassValidation = false; } diff --git a/libs/common/src/vault/models/domain/folder.spec.ts b/libs/common/src/vault/models/domain/folder.spec.ts index ff1c38bdd45..2c35f427e40 100644 --- a/libs/common/src/vault/models/domain/folder.spec.ts +++ b/libs/common/src/vault/models/domain/folder.spec.ts @@ -70,7 +70,7 @@ describe("Folder", () => { beforeEach(() => { encryptService = mock(); - encryptService.decryptToUtf8.mockImplementation((value) => { + encryptService.decryptString.mockImplementation((value) => { return Promise.resolve(value.data); }); }); diff --git a/libs/common/src/vault/services/cipher.service.spec.ts b/libs/common/src/vault/services/cipher.service.spec.ts index 57df5f2a376..01e99232c7a 100644 --- a/libs/common/src/vault/services/cipher.service.spec.ts +++ b/libs/common/src/vault/services/cipher.service.spec.ts @@ -131,8 +131,8 @@ describe("Cipher Service", () => { let cipherObj: Cipher; beforeEach(() => { - encryptService.encryptToBytes.mockReturnValue(Promise.resolve(ENCRYPTED_BYTES)); - encryptService.encrypt.mockReturnValue(Promise.resolve(new EncString(ENCRYPTED_TEXT))); + encryptService.encryptFileData.mockReturnValue(Promise.resolve(ENCRYPTED_BYTES)); + encryptService.encryptString.mockReturnValue(Promise.resolve(new EncString(ENCRYPTED_TEXT))); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); @@ -274,12 +274,12 @@ describe("Cipher Service", () => { cipherView = new CipherView(); cipherView.type = CipherType.Login; - encryptService.decryptToBytes.mockReturnValue(Promise.resolve(makeStaticByteArray(64))); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64))); configService.checkServerMeetsVersionRequirement$.mockReturnValue(of(true)); keyService.makeCipherKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(makeStaticByteArray(64)) as CipherKey), ); - encryptService.encrypt.mockImplementation(encryptText); + encryptService.encryptString.mockImplementation(encryptText); encryptService.wrapSymmetricKey.mockResolvedValue(new EncString("Re-encrypted Cipher Key")); jest.spyOn(cipherService as any, "getAutofillOnPageLoadDefault").mockResolvedValue(true); @@ -435,7 +435,7 @@ describe("Cipher Service", () => { .spyOn(cipherService, "failedToDecryptCiphers$") .mockImplementation((userId: UserId) => failedCiphers); - encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(32)); + encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(new Uint8Array(32))); encryptedKey = new EncString("Re-encrypted Cipher Key"); encryptService.wrapSymmetricKey.mockResolvedValue(encryptedKey); diff --git a/libs/common/src/vault/services/cipher.service.ts b/libs/common/src/vault/services/cipher.service.ts index 455be3babea..acc211686fc 100644 --- a/libs/common/src/vault/services/cipher.service.ts +++ b/libs/common/src/vault/services/cipher.service.ts @@ -881,9 +881,7 @@ export class CipherService implements CipherServiceAbstraction { const cipherEncKey = cipherKeyEncryptionEnabled && cipher.key != null - ? (new SymmetricCryptoKey( - await this.encryptService.decryptToBytes(cipher.key, encKey), - ) as UserKey) + ? (await this.encryptService.unwrapSymmetricKey(cipher.key, encKey) as UserKey) : encKey; //if cipher key encryption is disabled but the item has an individual key, @@ -895,10 +893,10 @@ export class CipherService implements CipherServiceAbstraction { await this.updateWithServer(cipher); } - const encFileName = await this.encryptService.encrypt(filename, cipherEncKey); + const encFileName = await this.encryptService.encryptString(filename, cipherEncKey); const dataEncKey = await this.keyService.makeDataEncKey(cipherEncKey); - const encData = await this.encryptService.encryptToBytes(new Uint8Array(data), dataEncKey[0]); + const encData = await this.encryptService.encryptFileData(new Uint8Array(data), dataEncKey[0]); const response = await this.cipherFileUploadService.upload( cipher, @@ -1490,7 +1488,7 @@ export class CipherService implements CipherServiceAbstraction { const encBuf = await EncArrayBuffer.fromResponse(attachmentResponse); const activeUserId = await firstValueFrom(this.accountService.activeAccount$); const userKey = await this.keyService.getUserKeyWithLegacySupport(activeUserId.id); - const decBuf = await this.encryptService.decryptToBytes(encBuf, userKey); + const decBuf = await this.encryptService.decryptFileData(encBuf, userKey); let encKey: UserKey | OrgKey; encKey = await this.keyService.getOrgKey(organizationId); @@ -1498,8 +1496,8 @@ export class CipherService implements CipherServiceAbstraction { const dataEncKey = await this.keyService.makeDataEncKey(encKey); - const encFileName = await this.encryptService.encrypt(attachmentView.fileName, encKey); - const encData = await this.encryptService.encryptToBytes(new Uint8Array(decBuf), dataEncKey[0]); + const encFileName = await this.encryptService.encryptString(attachmentView.fileName, encKey); + const encData = await this.encryptService.encryptFileData(new Uint8Array(decBuf), dataEncKey[0]); const fd = new FormData(); try { @@ -1554,7 +1552,7 @@ export class CipherService implements CipherServiceAbstraction { .then(() => { const modelProp = (model as any)[map[theProp] || theProp]; if (modelProp && modelProp !== "") { - return self.encryptService.encrypt(modelProp, key); + return self.encryptService.encryptString(modelProp, key); } return null; }) @@ -1600,7 +1598,7 @@ export class CipherService implements CipherServiceAbstraction { key, ); const uriHash = await this.encryptService.hash(model.login.uris[i].uri, "sha256"); - loginUri.uriChecksum = await this.encryptService.encrypt(uriHash, key); + loginUri.uriChecksum = await this.encryptService.encryptString(uriHash, key); cipher.login.uris.push(loginUri); } } @@ -1627,8 +1625,8 @@ export class CipherService implements CipherServiceAbstraction { }, key, ); - domainKey.counter = await this.encryptService.encrypt(String(viewKey.counter), key); - domainKey.discoverable = await this.encryptService.encrypt( + domainKey.counter = await this.encryptService.encryptString(String(viewKey.counter), key); + domainKey.discoverable = await this.encryptService.encryptString( String(viewKey.discoverable), key, ); @@ -1814,9 +1812,7 @@ export class CipherService implements CipherServiceAbstraction { if (cipher.key == null) { decryptedCipherKey = await this.keyService.makeCipherKey(); } else { - decryptedCipherKey = new SymmetricCryptoKey( - await this.encryptService.decryptToBytes(cipher.key, keyForCipherKeyDecryption), - ); + decryptedCipherKey = await this.encryptService.unwrapSymmetricKey(cipher.key, keyForCipherKeyDecryption); } // Then, we have to encrypt the cipher key with the proper key. diff --git a/libs/common/src/vault/services/folder/folder.service.spec.ts b/libs/common/src/vault/services/folder/folder.service.spec.ts index ced4e2dceb7..9f26c7109a8 100644 --- a/libs/common/src/vault/services/folder/folder.service.spec.ts +++ b/libs/common/src/vault/services/folder/folder.service.spec.ts @@ -46,7 +46,7 @@ describe("Folder Service", () => { i18nService.t.mockReturnValue("No Folder"); keyService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); - encryptService.decryptToUtf8.mockResolvedValue("DEC"); + encryptService.decryptString.mockResolvedValue("DEC"); folderService = new FolderService( keyService, @@ -110,7 +110,7 @@ describe("Folder Service", () => { model.id = "2"; model.name = "Test Folder"; - encryptService.encrypt.mockResolvedValue(new EncString("ENC")); + encryptService.encryptString.mockResolvedValue(new EncString("ENC")); const result = await folderService.encrypt(model, null); @@ -211,7 +211,7 @@ describe("Folder Service", () => { beforeEach(() => { encryptedKey = new EncString("Re-encrypted Folder"); - encryptService.encrypt.mockResolvedValue(encryptedKey); + encryptService.encryptString.mockResolvedValue(encryptedKey); }); it("returns re-encrypted user folders", async () => { diff --git a/libs/common/src/vault/services/folder/folder.service.ts b/libs/common/src/vault/services/folder/folder.service.ts index 89bc5353f88..ba87f1c3148 100644 --- a/libs/common/src/vault/services/folder/folder.service.ts +++ b/libs/common/src/vault/services/folder/folder.service.ts @@ -84,7 +84,7 @@ export class FolderService implements InternalFolderServiceAbstraction { async encrypt(model: FolderView, key: SymmetricCryptoKey): Promise { const folder = new Folder(); folder.id = model.id; - folder.name = await this.encryptService.encrypt(model.name, key); + folder.name = await this.encryptService.encryptString(model.name, key); return folder; } diff --git a/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts b/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts index f01e6571439..9284718a063 100644 --- a/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts +++ b/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts @@ -72,7 +72,7 @@ export class BitwardenJsonImporter extends BaseImporter implements Importer { keyForDecryption = await this.keyService.getUserKeyWithLegacySupport(); } const encKeyValidation = new EncString(results.encKeyValidation_DO_NOT_EDIT); - const encKeyValidationDecrypt = await this.encryptService.decryptToUtf8( + const encKeyValidationDecrypt = await this.encryptService.decryptString( encKeyValidation, keyForDecryption, ); diff --git a/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.spec.ts b/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.spec.ts index 66deabf0634..8d0f5dfcc1c 100644 --- a/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.spec.ts +++ b/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.spec.ts @@ -92,7 +92,7 @@ describe("BitwardenPasswordProtectedImporter", () => { }); it("succeeds with default jdoc", async () => { - encryptService.decryptToUtf8.mockReturnValue(Promise.resolve(emptyUnencryptedExport)); + encryptService.decryptString.mockReturnValue(Promise.resolve(emptyUnencryptedExport)); expect((await importer.parse(JSON.stringify(jDoc))).success).toEqual(true); }); diff --git a/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts b/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts index 02a417c2169..878f9cf5819 100644 --- a/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts +++ b/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts @@ -69,7 +69,7 @@ export class BitwardenPasswordProtectedImporter extends BitwardenJsonImporter im } const encData = new EncString(parsedData.data); - const clearTextData = await this.encryptService.decryptToUtf8(encData, this.key); + const clearTextData = await this.encryptService.decryptString(encData, this.key); return await super.parse(clearTextData); } @@ -90,7 +90,7 @@ export class BitwardenPasswordProtectedImporter extends BitwardenJsonImporter im const encKeyValidation = new EncString(jdoc.encKeyValidation_DO_NOT_EDIT); - const encKeyValidationDecrypt = await this.encryptService.decryptToUtf8( + const encKeyValidationDecrypt = await this.encryptService.decryptString( encKeyValidation, this.key, ); diff --git a/libs/key-management/src/key.service.spec.ts b/libs/key-management/src/key.service.spec.ts index 90d049b7293..b824cf96aff 100644 --- a/libs/key-management/src/key.service.spec.ts +++ b/libs/key-management/src/key.service.spec.ts @@ -330,7 +330,7 @@ describe("keyService", () => { everHadUserKeyState.nextState(null); // Mock private key decryption - encryptService.decryptToBytes.mockResolvedValue(mockRandomBytes); + encryptService.unwrapDecapsulationKey.mockResolvedValue(mockRandomBytes); }); it("throws if userKey is null", async () => { @@ -352,7 +352,7 @@ describe("keyService", () => { }); it("throws if encPrivateKey cannot be decrypted with the userKey", async () => { - encryptService.decryptToBytes.mockResolvedValue(null); + encryptService.unwrapDecapsulationKey.mockResolvedValue(null); await expect( keyService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId), @@ -452,17 +452,16 @@ describe("keyService", () => { // Decryption of the user private key const fakeDecryptedUserPrivateKey = makeStaticByteArray(10, 1); - encryptService.decryptToBytes.mockResolvedValue(fakeDecryptedUserPrivateKey); + encryptService.unwrapDecapsulationKey.mockResolvedValue(fakeDecryptedUserPrivateKey); const fakeUserPublicKey = makeStaticByteArray(10, 2); cryptoFunctionService.rsaExtractPublicKey.mockResolvedValue(fakeUserPublicKey); const userPrivateKey = await firstValueFrom(keyService.userPrivateKey$(mockUserId)); - expect(encryptService.decryptToBytes).toHaveBeenCalledWith( + expect(encryptService.unwrapDecapsulationKey).toHaveBeenCalledWith( fakeEncryptedUserPrivateKey, - userKey, - "Content: Encrypted Private Key", + userKey ); expect(userPrivateKey).toBe(fakeDecryptedUserPrivateKey); @@ -473,7 +472,7 @@ describe("keyService", () => { const userPrivateKey = await firstValueFrom(keyService.userPrivateKey$(mockUserId)); - expect(encryptService.decryptToBytes).not.toHaveBeenCalled(); + expect(encryptService.unwrapDecapsulationKey).not.toHaveBeenCalled(); expect(userPrivateKey).toBeFalsy(); }); @@ -552,7 +551,7 @@ describe("keyService", () => { providerKeysState.nextState(keys.providerKeys!); } - encryptService.decryptToBytes.mockImplementation((encryptedPrivateKey, userKey) => { + encryptService.unwrapDecapsulationKey.mockImplementation((encryptedPrivateKey, userKey) => { // TOOD: Branch between provider and private key? return Promise.resolve(fakePrivateKeyDecryption(encryptedPrivateKey, userKey)); }); diff --git a/libs/key-management/src/key.service.ts b/libs/key-management/src/key.service.ts index 5dec206b86b..10df0dcba06 100644 --- a/libs/key-management/src/key.service.ts +++ b/libs/key-management/src/key.service.ts @@ -733,7 +733,7 @@ export class DefaultKeyService implements KeyServiceAbstraction { const storePin = await this.shouldStoreKey(KeySuffixOptions.Pin, userId); if (storePin) { // Decrypt userKeyEncryptedPin with user key - const pin = await this.encryptService.decryptToUtf8( + const pin = await this.encryptService.decryptString( (await this.pinService.getUserKeyEncryptedPin(userId))!, key, ); @@ -940,10 +940,9 @@ export class DefaultKeyService implements KeyServiceAbstraction { return null; } - return (await this.encryptService.decryptToBytes( + return (await this.encryptService.unwrapDecapsulationKey( new EncString(encryptedPrivateKey), key, - "Content: Encrypted Private Key", )) as UserPrivateKey; } diff --git a/libs/key-management/src/user-asymmetric-key-regeneration/services/default-user-asymmetric-key-regeneration.service.spec.ts b/libs/key-management/src/user-asymmetric-key-regeneration/services/default-user-asymmetric-key-regeneration.service.spec.ts index af5828c5aed..c6e641af32d 100644 --- a/libs/key-management/src/user-asymmetric-key-regeneration/services/default-user-asymmetric-key-regeneration.service.spec.ts +++ b/libs/key-management/src/user-asymmetric-key-regeneration/services/default-user-asymmetric-key-regeneration.service.spec.ts @@ -58,7 +58,7 @@ function setupUserKeyValidation( cipher.notes = mockEnc("EncryptedString"); cipher.key = mockEnc("EncKey"); cipherService.getAll.mockResolvedValue([cipher]); - encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); + encryptService.decryptFileData.mockResolvedValue(makeStaticByteArray(64)); (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); } @@ -279,7 +279,7 @@ describe("regenerateIfNeeded", () => { }; setupVerificationResponse(mockVerificationResponse, sdkService); setupUserKeyValidation(cipherService, keyService, encryptService); - encryptService.decryptToBytes.mockRejectedValue(new Error("error")); + encryptService.decryptFileData.mockRejectedValue(new Error("error")); await sut.regenerateIfNeeded(userId); @@ -328,7 +328,7 @@ describe("regenerateIfNeeded", () => { }; setupVerificationResponse(mockVerificationResponse, sdkService); setupUserKeyValidation(cipherService, keyService, encryptService); - encryptService.decryptToBytes.mockRejectedValue(new Error("error")); + encryptService.decryptFileData.mockRejectedValue(new Error("error")); await sut.regenerateIfNeeded(userId); diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/base-vault-export.service.ts b/libs/tools/export/vault-export/vault-export-core/src/services/base-vault-export.service.ts index 0a92f4f02d7..381b0b65a9f 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/base-vault-export.service.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/base-vault-export.service.ts @@ -23,8 +23,8 @@ export class BaseVaultExportService { const salt = Utils.fromBufferToB64(await this.cryptoFunctionService.randomBytes(16)); const key = await this.pinService.makePinKey(password, salt, kdfConfig); - const encKeyValidation = await this.encryptService.encrypt(Utils.newGuid(), key); - const encText = await this.encryptService.encrypt(clearText, key); + const encKeyValidation = await this.encryptService.encryptString(Utils.newGuid(), key); + const encText = await this.encryptService.encryptString(clearText, key); const jsonDoc: BitwardenPasswordProtectedFileFormat = { encrypted: true, diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts index 15791ae04fb..ae408af421b 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts @@ -209,7 +209,7 @@ describe("VaultExportService", () => { folderService.folderViews$.mockReturnValue(of(UserFolderViews)); folderService.folders$.mockReturnValue(of(UserFolders)); kdfConfigService.getKdfConfig.mockResolvedValue(DEFAULT_KDF_CONFIG); - encryptService.encrypt.mockResolvedValue(new EncString("encrypted")); + encryptService.encryptString.mockResolvedValue(new EncString("encrypted")); apiService.getAttachmentData.mockResolvedValue(attachmentResponse); exportService = new IndividualVaultExportService( @@ -313,7 +313,7 @@ describe("VaultExportService", () => { cipherService.getAllDecrypted.mockResolvedValue([cipherView]); folderService.getAllDecryptedFromState.mockResolvedValue([]); - encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(255)); + encryptService.decryptFileData.mockResolvedValue(new Uint8Array(255)); global.fetch = jest.fn(() => Promise.resolve({ @@ -338,7 +338,7 @@ describe("VaultExportService", () => { cipherService.getAllDecrypted.mockResolvedValue([cipherView]); folderService.getAllDecryptedFromState.mockResolvedValue([]); - encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(255)); + encryptService.decryptFileData.mockResolvedValue(new Uint8Array(255)); global.fetch = jest.fn(() => Promise.resolve({ @@ -362,7 +362,7 @@ describe("VaultExportService", () => { cipherView.attachments = [attachmentView]; cipherService.getAllDecrypted.mockResolvedValue([cipherView]); folderService.getAllDecryptedFromState.mockResolvedValue([]); - encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(255)); + encryptService.decryptFileData.mockResolvedValue(new Uint8Array(255)); global.fetch = jest.fn(() => Promise.resolve({ status: 200, @@ -427,7 +427,7 @@ describe("VaultExportService", () => { }); it("has a mac property", async () => { - encryptService.encrypt.mockResolvedValue(mac); + encryptService.encryptString.mockResolvedValue(mac); exportedVault = await exportService.getPasswordProtectedExport(password); exportString = exportedVault.data; exportObject = JSON.parse(exportString); @@ -436,7 +436,7 @@ describe("VaultExportService", () => { }); it("has data property", async () => { - encryptService.encrypt.mockResolvedValue(data); + encryptService.encryptString.mockResolvedValue(data); exportedVault = await exportService.getPasswordProtectedExport(password); exportString = exportedVault.data; exportObject = JSON.parse(exportString); diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts index d253ae8d0b1..8271edaccf7 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts @@ -155,7 +155,7 @@ export class IndividualVaultExportService attachment.key != null ? attachment.key : await this.keyService.getOrgKey(cipher.organizationId); - return await this.encryptService.decryptToBytes(encBuf, key); + return await this.encryptService.decryptFileData(encBuf, key); } catch { throw new Error("Error decrypting attachment"); } @@ -219,7 +219,7 @@ export class IndividualVaultExportService const userKey = await this.keyService.getUserKeyWithLegacySupport( await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId)), ); - const encKeyValidation = await this.encryptService.encrypt(Utils.newGuid(), userKey); + const encKeyValidation = await this.encryptService.encryptString(Utils.newGuid(), userKey); const jsonDoc: BitwardenEncryptedIndividualJsonExport = { encrypted: true, diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts b/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts index e4ed105d1ad..d8951d94d95 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts @@ -282,7 +282,7 @@ export class OrganizationVaultExportService ciphers: Cipher[], ): Promise { const orgKey = await this.keyService.getOrgKey(organizationId); - const encKeyValidation = await this.encryptService.encrypt(Utils.newGuid(), orgKey); + const encKeyValidation = await this.encryptService.encryptString(Utils.newGuid(), orgKey); const jsonDoc: BitwardenEncryptedOrgJsonExport = { encrypted: true, diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts b/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts index a90f0a3ed7b..4e0dbfcc330 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts @@ -175,7 +175,7 @@ describe("VaultExportService", () => { folderService.folderViews$.mockReturnValue(of(UserFolderViews)); folderService.folders$.mockReturnValue(of(UserFolders)); kdfConfigService.getKdfConfig.mockResolvedValue(DEFAULT_KDF_CONFIG); - encryptService.encrypt.mockResolvedValue(new EncString("encrypted")); + encryptService.encryptString.mockResolvedValue(new EncString("encrypted")); keyService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); const userId = "" as UserId; const accountInfo: AccountInfo = { @@ -282,7 +282,7 @@ describe("VaultExportService", () => { }); it("has a mac property", async () => { - encryptService.encrypt.mockResolvedValue(mac); + encryptService.encryptString.mockResolvedValue(mac); exportedVault = await exportService.getPasswordProtectedExport(password); @@ -293,7 +293,7 @@ describe("VaultExportService", () => { }); it("has data property", async () => { - encryptService.encrypt.mockResolvedValue(data); + encryptService.encryptString.mockResolvedValue(data); exportedVault = await exportService.getPasswordProtectedExport(password); diff --git a/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts b/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts index 06113ee9b99..4278f7e0e08 100644 --- a/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts +++ b/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts @@ -19,7 +19,7 @@ export class LegacyPasswordHistoryDecryptor { const promises = (history ?? []).map(async (item) => { const encrypted = new EncString(item.password); - const decrypted = await this.encryptService.decryptToUtf8(encrypted, key); + const decrypted = await this.encryptService.decryptString(encrypted, key); return new GeneratedPasswordHistory(decrypted, item.date); }); diff --git a/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts b/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts index b3dee69bdbf..b20e3e6365f 100644 --- a/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts +++ b/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts @@ -22,8 +22,8 @@ describe("LocalGeneratorHistoryService", () => { const userKey = new SymmetricCryptoKey(new Uint8Array(64) as CsprngArray) as UserKey; beforeEach(() => { - encryptService.encrypt.mockImplementation((p) => Promise.resolve(p as unknown as EncString)); - encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c.encryptedString)); + encryptService.encryptString.mockImplementation((p) => Promise.resolve(p as unknown as EncString)); + encryptService.decryptString.mockImplementation((c) => Promise.resolve(c.encryptedString)); keyService.getUserKey.mockImplementation(() => Promise.resolve(userKey)); keyService.userKey$.mockImplementation(() => of(true as unknown as UserKey)); }); diff --git a/libs/vault/src/components/download-attachment/download-attachment.component.ts b/libs/vault/src/components/download-attachment/download-attachment.component.ts index 812051775f8..fb11774a40a 100644 --- a/libs/vault/src/components/download-attachment/download-attachment.component.ts +++ b/libs/vault/src/components/download-attachment/download-attachment.component.ts @@ -97,7 +97,7 @@ export class DownloadAttachmentComponent { try { const encBuf = await EncArrayBuffer.fromResponse(response); const key = this.attachment.key != null ? this.attachment.key : this.orgKey; - const decBuf = await this.encryptService.decryptToBytes(encBuf, key); + const decBuf = await this.encryptService.decryptFileData(encBuf, key); this.fileDownloadService.download({ fileName: this.attachment.fileName, blobData: decBuf,