1
0
mirror of https://github.com/bitwarden/browser synced 2026-02-09 13:10:17 +00:00
This commit is contained in:
Bernd Schoolmann
2025-04-24 18:33:37 +02:00
parent fbc520b242
commit 11fb36e7e0
75 changed files with 229 additions and 274 deletions

View File

@@ -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 {

View File

@@ -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();
},
);
});

View File

@@ -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",

View File

@@ -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);

View File

@@ -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}`,

View File

@@ -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;

View File

@@ -228,7 +228,7 @@ export default class NativeMessageService {
key: string,
): Promise<DecryptedCommandData> {
const sharedKey = await this.getSharedKeyForKey(key);
const decrypted = await this.encryptService.decryptToUtf8(
const decrypted = await this.encryptService.decryptString(
payload,
sharedKey,
"native-messaging-session",

View File

@@ -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,

View File

@@ -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),
),

View File

@@ -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",

View File

@@ -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,
);

View File

@@ -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);
}));

View File

@@ -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<PasswordHealthReportApplicationsRequest[]> {
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() ?? "",

View File

@@ -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,
);

View File

@@ -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,
);

View File

@@ -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", () => {

View File

@@ -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;
}),

View File

@@ -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);

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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;

View File

@@ -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();

View File

@@ -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;

View File

@@ -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),

View File

@@ -120,7 +120,7 @@ const mockStateProvider = () => {
const mockCryptoService = () => {
const keyService = mock<KeyService>();
const encryptService = mock<EncryptService>();
encryptService.decryptToUtf8
encryptService.decryptString
.calledWith(expect.any(EncString), expect.anything())
.mockResolvedValue("DECRYPTED_STRING");

View File

@@ -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;
}

View File

@@ -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),

View File

@@ -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;
}

View File

@@ -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),
);

View File

@@ -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,

View File

@@ -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);

View File

@@ -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,
);

View File

@@ -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<PinKey> {
@@ -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;

View File

@@ -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);

View File

@@ -56,14 +56,14 @@ export class ProviderEncryptedOrganizationKey implements BaseEncryptedOrganizati
) {}
async decrypt(encryptService: EncryptService, providerKeys: Record<string, SymmetricCryptoKey>) {
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() {

View File

@@ -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);

View File

@@ -289,7 +289,7 @@ export class TokenService implements TokenServiceAbstraction {
private async encryptAccessToken(accessToken: string, userId: UserId): Promise<EncString> {
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,
);

View File

@@ -120,7 +120,7 @@ export class OrganizationBillingService implements OrganizationBillingServiceAbs
private async makeOrganizationKeys(): Promise<OrganizationKeys> {
const [encryptedKey, key] = await this.keyService.makeOrgKey<OrgKey>();
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,
);

View File

@@ -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,
);

View File

@@ -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);

View File

@@ -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;
}
}

View File

@@ -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"],

View File

@@ -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>();
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<KeyService>();
const encryptService = mock<EncryptService>();
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",
);
});
});

View File

@@ -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) {

View File

@@ -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(<T>(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);
});

View File

@@ -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>(secret: EncString): Promise<Jsonify<Secret>> {
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<Secret>(decrypted);
decrypted = null;

View File

@@ -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(<T>(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);
});

View File

@@ -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>(secret: EncString): Promise<Jsonify<Secret>> {
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<Secret>(decrypted);
decrypted = null;

View File

@@ -112,7 +112,7 @@ describe("Send", () => {
const encryptService = mock<EncryptService>();
const keyService = mock<KeyService>();
encryptService.decryptToBytes
encryptService.decryptBytes
.calledWith(send.key, userKey)
.mockResolvedValue(makeStaticByteArray(32));
keyService.makeSendKey.mockResolvedValue("cryptoKey" as any);

View File

@@ -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

View File

@@ -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);
});

View File

@@ -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];
}

View File

@@ -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);
});
});
});

View File

@@ -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) {

View File

@@ -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<EncryptService>();
const cipherService = mock<CipherService>();
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<EncryptService>();
const cipherService = mock<CipherService>();
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<EncryptService>();
const cipherService = mock<CipherService>();
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<EncryptService>();
const cipherService = mock<CipherService>();
encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64));
encryptService.unwrapSymmetricKey.mockResolvedValue(new SymmetricCryptoKey(makeStaticByteArray(64)));
(window as any).bitwardenContainerService = new ContainerService(keyService, encryptService);

View File

@@ -143,17 +143,16 @@ export class Cipher extends Domain implements Decryptable<CipherView> {
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;
}

View File

@@ -70,7 +70,7 @@ describe("Folder", () => {
beforeEach(() => {
encryptService = mock<EncryptService>();
encryptService.decryptToUtf8.mockImplementation((value) => {
encryptService.decryptString.mockImplementation((value) => {
return Promise.resolve(value.data);
});
});

View File

@@ -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);

View File

@@ -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.

View File

@@ -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 () => {

View File

@@ -84,7 +84,7 @@ export class FolderService implements InternalFolderServiceAbstraction {
async encrypt(model: FolderView, key: SymmetricCryptoKey): Promise<Folder> {
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;
}

View File

@@ -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,
);

View File

@@ -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);
});

View File

@@ -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,
);

View File

@@ -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));
});

View File

@@ -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;
}

View File

@@ -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);

View File

@@ -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,

View File

@@ -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);

View File

@@ -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,

View File

@@ -282,7 +282,7 @@ export class OrganizationVaultExportService
ciphers: Cipher[],
): Promise<string> {
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,

View File

@@ -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);

View File

@@ -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);
});

View File

@@ -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));
});

View File

@@ -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,