openpgp.decrypt returning empty string when running on jest

246 views Asked by At

I have the following function, I am using TypeScript and the library OpenPGP JS

import * as openpgp from "openpgp";

export async function decryptMessage(
  privateKeyArmored: string,
  passphrase: string,
  encrypted: string
) {
  const {
    keys: [privateKey]
  } = await openpgp.key.readArmored(privateKeyArmored);

  await privateKey.decrypt(passphrase);

  const { data: decrypted } = await openpgp.decrypt({
    message: await openpgp.message.readArmored(encrypted),
    privateKeys: [privateKey]
  });

  return decrypted;
}

And my unit-test:

import * as openpgp from "openpgp";

import { decryptMessage } from "../src/crypto";

const oldTextEncoder = global.TextEncoder;
const oldTextDecoder = global.TextDecoder;

describe("crypto", () => {
  const passphrase = "test";
  let privateKey: string;
  let publicKey: string;

  beforeAll(async () => {
    const textEncoding = await import("text-encoding-utf-8");
    global.TextEncoder = textEncoding.TextEncoder;
    global.TextDecoder = textEncoding.TextDecoder;

    const { privateKeyArmored, publicKeyArmored } = await openpgp.generateKey({
      userIds: [{ name: "username" }],
      curve: "ed25519",
      passphrase
    });

    privateKey = privateKeyArmored;
    publicKey = publicKeyArmored;
  });

  afterAll(() => {
    global.TextEncoder = oldTextEncoder;
    global.TextDecoder = oldTextDecoder;
  });

  test("decrypt message", async () => {
    const text = "test"

    const { data: encrypted } = await openpgp.encrypt({
      message: openpgp.message.fromText(text),
      publicKeys: (await openpgp.key.readArmored(publicKey)).keys,
    });

    const result = await decryptMessage(privateKey, passphrase, encrypted);

    expect(result).toBe(text);
  });
});

On the line expect(result).toBe(text); I am receiving a empty string and my test fails

expect(received).toBe(expected) // Object.is equality

Expected: "test"
Received: ""

This function works in production, but running under jest there is no warnings, just return an empty string.

If I change the password I got an exception, so the code is fine, is there something under the jest enviroment.

Am I missing something?

0

There are 0 answers