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
3 changes: 0 additions & 3 deletions src/api/pdf-signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,6 @@ export class PDFSignature {
const formatBuilder = this.getFormatBuilder(resolved.subFilter);

// Create the CMS structure (signs the document)
// Note: PDFBox includes signingTime even when using a timestamp.
// The timestamp provides the authoritative time, but signingTime
// may be needed for Adobe to recognize the timestamp token.
const signedData = await formatBuilder.create({
signer: resolved.signer,
documentHash,
Expand Down
20 changes: 20 additions & 0 deletions src/integration/signatures/signing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
*/

import { PDF } from "#src/api/pdf";
import { hexToBytes } from "#src/helpers/buffer";
import { getSignedAttributeOids } from "#src/signatures/formats/test-helpers";
import { OID_SIGNING_TIME } from "#src/signatures/oids";
import { P12Signer } from "#src/signatures/signers";
import { HttpTimestampAuthority } from "#src/signatures/timestamp";
import { loadFixture, saveTestOutput } from "#src/test-utils";
Expand Down Expand Up @@ -97,6 +100,23 @@ describe("signing integration", { timeout: NETWORK_TEST_TIMEOUT }, () => {
expect(pdfStr).toContain("/ContactInfo (test@example.com)");
expect(pdfStr).toContain("/M (D:20250105120000Z)");
});

it("forwards signingTime into the CMS for adbe.pkcs7.detached", async () => {
const pdfBytes = await loadFixture("basic", "rot0.pdf");
const pdf = await PDF.load(pdfBytes);
const signer = await loadTestSigner();

const { bytes } = await pdf.sign({
signer,
subFilter: "adbe.pkcs7.detached",
signingTime: new Date("2025-01-05T12:00:00Z"),
});

const pdfStr = new TextDecoder().decode(bytes);
const contentsHex = pdfStr.match(/\/Contents\s*<([0-9A-Fa-f]+)>/)?.[1] ?? "";

expect(getSignedAttributeOids(hexToBytes(contentsHex))).toContain(OID_SIGNING_TIME);
});
});

describe("B-T signing (with timestamp)", () => {
Expand Down
21 changes: 21 additions & 0 deletions src/signatures/formats/cades-detached.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";

import { OID_CONTENT_TYPE, OID_MESSAGE_DIGEST, OID_SIGNING_CERTIFICATE_V2 } from "../oids";
import { hashData } from "../utils";
import { CAdESDetachedBuilder } from "./cades-detached";
import { getSignedAttributeOids, loadTestSigner } from "./test-helpers";

describe("CAdESDetachedBuilder", () => {
it("emits only the PAdES baseline signed attributes, ignoring signingTime", async () => {
const signedData = await new CAdESDetachedBuilder().create({
signer: await loadTestSigner(),
documentHash: await hashData(new TextEncoder().encode("hello"), "SHA-256"),
digestAlgorithm: "SHA-256",
signingTime: new Date("2025-01-05T12:00:00Z"),
});

expect(getSignedAttributeOids(signedData.toDER()).sort()).toEqual(
[OID_CONTENT_TYPE, OID_MESSAGE_DIGEST, OID_SIGNING_CERTIFICATE_V2].sort(),
);
});
});
41 changes: 11 additions & 30 deletions src/signatures/formats/cades-detached.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
/**
* CAdES Detached signature format (ETSI.CAdES.detached).
*
* This is the modern PAdES-compliant signature format. It extends PKCS#7 with:
* - ESS signing-certificate-v2 attribute (binds certificate to signature)
* - Content hints (optional)
* This is the modern PAdES-compliant signature format. It extends PKCS#7 with
* the ESS signing-certificate-v2 attribute (binds certificate to signature).
*
* ETSI EN 319 122-1: CAdES digital signatures
* ETSI EN 319 142-1: PAdES digital signatures
*/

import { fromBER, ObjectIdentifier, OctetString, Sequence, UTCTime } from "asn1js";
import { fromBER, ObjectIdentifier, OctetString, Sequence } from "asn1js";
import * as pkijs from "pkijs";

import { toArrayBuffer } from "../../helpers/buffer";
Expand All @@ -22,13 +21,11 @@ import {
OID_SHA512,
OID_SIGNED_DATA,
OID_SIGNING_CERTIFICATE_V2,
OID_SIGNING_TIME,
OID_TIMESTAMP_TOKEN,
} from "../oids";
import type { DigestAlgorithm, Signer } from "../types";
import type { DigestAlgorithm } from "../types";
import { hashData } from "../utils";
import {
buildCMSAlgorithmProtection,
encodeSignedAttributesForSigning,
getDigestAlgorithmOid,
getSignatureAlgorithmOid,
Expand All @@ -54,21 +51,15 @@ export class CAdESDetachedBuilder implements CMSFormatBuilder, CMSSignedData {
* being serialized to DER.
*/
async create(options: CMSCreateOptions): Promise<CMSSignedData> {
const { signer, documentHash, digestAlgorithm, signingTime } = options;
const { signer, documentHash, digestAlgorithm } = options;

// Parse certificates
const signerCert = parseCertificate(signer.certificate);
const chainCerts = (signer.certificateChain ?? []).map(parseCertificate);
const allCerts = [signerCert, ...chainCerts];

// Build signed attributes
const signedAttrs = await this.buildSignedAttributes(
documentHash,
digestAlgorithm,
signer,
signerCert,
signingTime,
);
const signedAttrs = await this.buildSignedAttributes(documentHash, digestAlgorithm, signerCert);

// Encode and sign
const signedAttrsForSigning = encodeSignedAttributesForSigning(signedAttrs);
Expand Down Expand Up @@ -150,13 +141,16 @@ export class CAdESDetachedBuilder implements CMSFormatBuilder, CMSSignedData {

/**
* Build the signed attributes for CAdES signature.
*
* Deliberately omitted, per ETSI EN 319 142-1 Table 1 / clause 6.3:
* - signing-time: "shall not be present" at every level; /M carries it.
* - cms-algorithm-protection: defined in EN 319 122-1 §5.2.13 but not
* listed in Table 1, and 6.3 forbids any such 122-1 attribute.
*/
private async buildSignedAttributes(
documentHash: Uint8Array,
digestAlgorithm: DigestAlgorithm,
signer: Signer,
signerCert: pkijs.Certificate,
signingTime?: Date,
): Promise<pkijs.Attribute[]> {
const attrs: pkijs.Attribute[] = [];

Expand All @@ -168,19 +162,6 @@ export class CAdESDetachedBuilder implements CMSFormatBuilder, CMSSignedData {
}),
);

// Signing Time (optional but recommended)
if (signingTime) {
attrs.push(
new pkijs.Attribute({
type: OID_SIGNING_TIME,
values: [new UTCTime({ valueDate: signingTime })],
}),
);
}

// CMS Algorithm Protection (RFC 6211)
attrs.push(buildCMSAlgorithmProtection(digestAlgorithm, signer));

// Message Digest (required)
attrs.push(
new pkijs.Attribute({
Expand Down
26 changes: 26 additions & 0 deletions src/signatures/formats/pkcs7-detached.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";

import {
OID_CMS_ALGORITHM_PROTECTION,
OID_CONTENT_TYPE,
OID_MESSAGE_DIGEST,
OID_SIGNING_TIME,
} from "../oids";
import { hashData } from "../utils";
import { PKCS7DetachedBuilder } from "./pkcs7-detached";
import { getSignedAttributeOids, loadTestSigner } from "./test-helpers";

describe("PKCS7DetachedBuilder", () => {
it("emits signing-time and cms-algorithm-protection signed attributes", async () => {
const signedData = await new PKCS7DetachedBuilder().create({
signer: await loadTestSigner(),
documentHash: await hashData(new TextEncoder().encode("hello"), "SHA-256"),
digestAlgorithm: "SHA-256",
signingTime: new Date("2025-01-05T12:00:00Z"),
});

expect(getSignedAttributeOids(signedData.toDER()).sort()).toEqual(
[OID_CONTENT_TYPE, OID_SIGNING_TIME, OID_CMS_ALGORITHM_PROTECTION, OID_MESSAGE_DIGEST].sort(),
);
});
});
39 changes: 39 additions & 0 deletions src/signatures/formats/test-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { fromBER } from "asn1js";
import * as pkijs from "pkijs";

import { toArrayBuffer } from "../../helpers/buffer";
import { loadFixture } from "../../test-utils";
import { OID_SIGNED_DATA } from "../oids";
import { P12Signer } from "../signers";

export async function loadTestSigner(): Promise<P12Signer> {
const p12Bytes = await loadFixture("certificates", "test-signer-aes256.p12");

return P12Signer.create(p12Bytes, "test123");
}

/**
* Attribute type OIDs of the first SignerInfo's signed attributes.
*/
export function getSignedAttributeOids(der: Uint8Array): string[] {
const asn1 = fromBER(toArrayBuffer(der));

if (asn1.offset === -1) {
throw new Error("Failed to parse CMS ContentInfo");
}

const contentInfo = new pkijs.ContentInfo({ schema: asn1.result });

if (contentInfo.contentType !== OID_SIGNED_DATA) {
throw new Error(`Expected SignedData, got ${contentInfo.contentType}`);
}

const signedData = new pkijs.SignedData({ schema: contentInfo.content });
const signerInfo = signedData.signerInfos[0];

if (!signerInfo) {
throw new Error("CMS has no SignerInfo");
}

return (signerInfo.signedAttrs?.attributes ?? []).map(attr => attr.type);
}
2 changes: 1 addition & 1 deletion src/signatures/formats/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface CMSCreateOptions {
/** Digest algorithm used */
digestAlgorithm: DigestAlgorithm;

/** Signing time (optional, embedded in signed attributes) */
/** Signing time for the signing-time signed attribute. Ignored by CAdES (PAdES forbids it). */
signingTime?: Date;
}

Expand Down
3 changes: 3 additions & 0 deletions src/signatures/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ export interface SignOptions {
* Signing time to embed in the signature.
* Defaults to current system time.
*
* Written to /M. Also embedded as a CMS signed attribute for
* `adbe.pkcs7.detached` only, since PAdES forbids it there.
*
* NOTE: This is NOT cryptographically verified - it's just a claim.
* The signer's local clock provides this value. For proven time,
* use a TimestampAuthority (B-T level or higher).
Expand Down
Loading