import { Substitute, SubstituteOf } from "@fluffy-spoon/substitute"; import { CryptoFunctionService } from "jslib-common/abstractions/cryptoFunction.service"; import { LogService } from "jslib-common/abstractions/log.service"; import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service"; import { StateService } from "jslib-common/abstractions/state.service"; import { SymmetricCryptoKey } from "jslib-common/models/domain/symmetricCryptoKey"; import { CryptoService } from "jslib-common/services/crypto.service"; import { WebCryptoFunctionService } from "jslib-common/services/webCryptoFunction.service"; import { makeStaticByteArray } from "../utils"; // Importing the wordlist crashes jest, mock it. jest.mock("jslib-common/misc/wordlist", () => ({ EEFLongWordList: [], })); describe("Crypto Service", () => { let cryptoFunctionService: CryptoFunctionService; let platformUtilsService: SubstituteOf; let logService: SubstituteOf; let stateService: SubstituteOf; let cryptoService: CryptoService; beforeEach(() => { cryptoFunctionService = new WebCryptoFunctionService(window); platformUtilsService = Substitute.for(); logService = Substitute.for(); stateService = Substitute.for(); cryptoService = new CryptoService( cryptoFunctionService, platformUtilsService, logService, stateService ); }); it("encrypt EncObject", async () => { const data = { name: "Random", }; const spy = jest .spyOn(cryptoFunctionService, "randomBytes") .mockImplementation(() => Promise.resolve(makeStaticByteArray(16))); const key = makeStaticByteArray(32); const symKey = new SymmetricCryptoKey(key.buffer); const encrypted = await cryptoService.encryptObject(data, symKey); expect(encrypted).toEqual({ encryptionType: 0, data: "HQjAyiEJss8N3xwNqJen8R4aE/XToFeV7LIBI7SYkTc=", iv: "AAECAwQFBgcICQoLDA0ODw==", mac: null, }); spy.mockRestore(); }); it("decrypt EncObject", async () => { const key = makeStaticByteArray(32); const symKey = new SymmetricCryptoKey(key.buffer); const decrypted = await cryptoService.decryptObject( { encryptionType: 0, data: "HQjAyiEJss8N3xwNqJen8R4aE/XToFeV7LIBI7SYkTc=", iv: "AAECAwQFBgcICQoLDA0ODw==", mac: null, }, symKey ); expect(decrypted).toEqual({ name: "Random", }); }); });