diff --git a/src/signatures/crypto/crypto-engine.test.ts b/src/signatures/crypto/crypto-engine.test.ts new file mode 100644 index 00000000..31062691 --- /dev/null +++ b/src/signatures/crypto/crypto-engine.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { CryptoEngine } from "./crypto-engine"; + +const data = new TextEncoder().encode("abc"); +const SHA256_ABC = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + +const hex = (buffer: ArrayBuffer) => + Array.from(new Uint8Array(buffer), b => b.toString(16).padStart(2, "0")).join(""); + +describe("CryptoEngine.digest", () => { + const engine = new CryptoEngine(); + + it("accepts the algorithm as an object", async () => { + expect(hex(await engine.digest({ name: "SHA-256" }, data))).toBe(SHA256_ABC); + }); + + it("accepts the algorithm as a bare string, as pkijs passes it during verification", async () => { + expect(hex(await engine.digest("SHA-256", data))).toBe(SHA256_ABC); + }); + + it("normalizes SHA256 to SHA-256 in both forms", async () => { + expect(hex(await engine.digest("SHA256", data))).toBe(SHA256_ABC); + expect(hex(await engine.digest({ name: "sha256" }, data))).toBe(SHA256_ABC); + }); +}); diff --git a/src/signatures/crypto/crypto-engine.ts b/src/signatures/crypto/crypto-engine.ts index ad85d47f..aec307d7 100644 --- a/src/signatures/crypto/crypto-engine.ts +++ b/src/signatures/crypto/crypto-engine.ts @@ -20,6 +20,8 @@ import { PKCS12KDF } from "./pkcs12-kdf"; import { RC2 } from "./rc2"; import { TripleDES } from "./triple-des"; +type AlgorithmIdentifier = string | { name: string }; + // ───────────────────────────────────────────────────────────────────────────── // OID Constants // ───────────────────────────────────────────────────────────────────────────── @@ -127,12 +129,14 @@ export class CryptoEngine extends pkijs.CryptoEngine { /** * Override digest to normalize algorithm names. * Web Crypto expects "SHA-256" but some code passes "SHA256". + * `algorithm` might be passed either as string or { name: string } by pkijs */ override async digest( - algorithm: { name: string }, + algorithm: AlgorithmIdentifier, data: ArrayBuffer | ArrayBufferView, ): Promise { - const normalizedAlgorithm = { ...algorithm }; + const normalizedAlgorithm = + typeof algorithm === "string" ? { name: algorithm } : { ...algorithm }; // Normalize hash algorithm names (SHA256 -> SHA-256) if (normalizedAlgorithm.name && !normalizedAlgorithm.name.includes("-")) {