Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/signatures/crypto/crypto-engine.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
8 changes: 6 additions & 2 deletions src/signatures/crypto/crypto-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
// ─────────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -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<ArrayBuffer> {
const normalizedAlgorithm = { ...algorithm };
const normalizedAlgorithm =
typeof algorithm === "string" ? { name: algorithm } : { ...algorithm };

// Normalize hash algorithm names (SHA256 -> SHA-256)
if (normalizedAlgorithm.name && !normalizedAlgorithm.name.includes("-")) {
Expand Down
Loading