A self hosted chat application with end-to-end encrypted messaging.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
1.2 KiB

  1. import { EncryptionService } from "./EncryptionService";
  2. import * as sjcl from "sjcl";
  3. import { MessageCipherDTO } from "../dto/MessageCipherDTO";
  4. import PromiseWorker from "promise-worker";
  5. export class SJCLEncryptionService implements EncryptionService {
  6. private _params: sjcl.SjclCipherParams = { mode: "gcm", ts: 128, adata: "", iter: 10000 };
  7. private readonly _promiseWorker: PromiseWorker;
  8. constructor(promiseWorker: PromiseWorker) {
  9. this._promiseWorker = promiseWorker;
  10. }
  11. public encrypt(passphrase: string, plainText: string): MessageCipherDTO {
  12. const fn = () => {
  13. // @ts-ignore
  14. const cipher = sjcl.encrypt(passphrase, plainText, this._params)
  15. return cipher as unknown as string
  16. }
  17. return JSON.parse(fn())
  18. }
  19. public decrypt(passphrase: string, cipher: MessageCipherDTO): string {
  20. return sjcl.decrypt(passphrase, JSON.stringify(cipher));
  21. }
  22. public async decryptAsPromise(passphrase: string, cipher: MessageCipherDTO): Promise<string> {
  23. const decrypted = await this._promiseWorker.postMessage({ "passphrase": passphrase, "cipher": cipher })
  24. return decrypted;
  25. }
  26. }