Skip to content
DemoSampleAPI ReferenceFAQ

PDF Generation Template Editor

Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.

View on GitHub

External and Two-Step Signing ​

When the private key lives on a smart card, in an HSM, or behind a remote signing service and cannot be handed to the SDK as a PKCS#12 file, use external signing. CPDFSignatureWorkflow offers three approaches. All of them ignore the signer property of CPDFSignatureCreateOptions:

ScenarioMethod
The key is in an HSM or remote service; the SDK builds the containersignExternalDetachedPKCS7ToPath:options:signer: with CPDFSignExternal
The signing appliance returns a complete CMS containersignWithContainerToPath:options:container: with CPDFSignContainer
Signing happens in another process or on another machineprepareSignatureToPath:options: → external signing → fillSignatureAtPath:options:

ComPDF SDK has no built-in PKCS#11 or cloud KMS adapter. To use such a key source, call the corresponding SDK or service from your CPDFSignExternal implementation.

Before choosing a signer, check Algorithms and Certificate Formats for the supported combinations and the distinction between raw signature values and complete CMS containers.

Sign with an External Private Key

When implementing the CPDFSignExternal protocol, note that:

  • signRequest: signs the data provided by the SDK and returns the raw signature value (for RSA, a block the size of the modulus; for ECDSA, the DER-encoded SEQUENCE { r, s }), never a container. dataKind describes the data; by default it is CPDFExternalSignDataKindSignedAttributes, the CMS SignedAttributes to sign.
  • The signature algorithm declared in CPDFExternalSignResult must match the one actually used. For example, declaring CPDFExternalSignatureAlgorithmRSAPKCS1v15 for an RSA-PSS signature produces a signature that fails validation.
  • On failure, return a result created with failureResultWithErrorCode:errorMessage:. Do not throw an exception, or the process will terminate.
  • When providesCertificate returns YES, supply the signing certificate and the intermediates through signerCertificateDER and certificateChainDER.

This example shows how to sign with an external private key:

swift
// Implement CPDFSignExternal. The private-key operation runs in an HSM or a remote signing service; the key never enters the app.
class RemoteSigner: NSObject, CPDFSignExternal {
    let certificateDER: Data
    let chainDER: [Data]

    init(certificateDER: Data, chainDER: [Data]) {
        self.certificateDER = certificateDER
        self.chainDER = chainDER
        super.init()
    }

    func signRequest(_ request: CPDFExternalSignRequest) -> CPDFExternalSignResult {
        // By default request.data is the DER-encoded CMS SignedAttributes,
        // so the service must digest it with request.digestAlgorithm before signing.
        guard let signatureValue = MySigningService.sign(request.data, digestAlgorithm: request.digestAlgorithm) else {
            return CPDFExternalSignResult.failureResultWithErrorCode("remote.unavailable", errorMessage: "The signing service did not respond.")
        }
        // Return the raw signature value (not a container) and the algorithm actually used.
        return CPDFExternalSignResult(signatureValue: signatureValue, algorithm: .rsapkcs1v15)
    }

    func providesCertificate() -> Bool {
        return true
    }

    func signerCertificateDER() -> Data? {
        return certificateDER
    }

    func certificateChainDER() -> [Data]? {
        return chainDER
    }
}

let options = CPDFSignatureCreateOptions()
options.profile = .pAdESB
options.fieldName = "Signature1"
options.pageIndex = 0
options.bounds = CGRect(x: 28, y: 420, width: 150, height: 70)
options.reason = "I am the owner of the document."

let remoteSigner = RemoteSigner(certificateDER: certificateDER, chainDER: chainDER)

// signRequest(_:) is called synchronously on the calling thread. Run this on a background queue.
DispatchQueue.global(qos: .userInitiated).async {
    let workflow = CPDFSignatureWorkflow(document: document)
    let result = workflow.signExternalDetachedPKCS7(toPath: signedFilePath, options: options, signer: remoteSigner)
    if !result.success {
        // The errorCode / errorMessage your signer returns appear verbatim in errors.
        for item in result.errors {
            print("\(item.code): \(item.message)")
        }
    }
}
objective-c
// Implement CPDFSignExternal. The private-key operation runs in an HSM or a remote signing service; the key never enters the app.
@interface RemoteSigner : NSObject <CPDFSignExternal>
@property (nonatomic, copy) NSData *certificateDER;
@property (nonatomic, copy) NSArray<NSData *> *chainDER;
@end

@implementation RemoteSigner

- (CPDFExternalSignResult *)signRequest:(CPDFExternalSignRequest *)request {
    // By default request.data is the DER-encoded CMS SignedAttributes,
    // so the service must digest it with request.digestAlgorithm before signing.
    NSData *signatureValue = [MySigningService sign:request.data digestAlgorithm:request.digestAlgorithm];
    if (!signatureValue) {
        return [CPDFExternalSignResult failureResultWithErrorCode:@"remote.unavailable" errorMessage:@"The signing service did not respond."];
    }
    // Return the raw signature value (not a container) and the algorithm actually used.
    return [CPDFExternalSignResult resultWithSignatureValue:signatureValue algorithm:CPDFExternalSignatureAlgorithmRSAPKCS1v15];
}

- (BOOL)providesCertificate {
    return YES;
}

- (NSData *)signerCertificateDER {
    return self.certificateDER;
}

- (NSArray<NSData *> *)certificateChainDER {
    return self.chainDER;
}

@end

CPDFSignatureCreateOptions *options = [[CPDFSignatureCreateOptions alloc] init];
options.profile = CPDFSignatureProfilePAdESB;
options.fieldName = @"Signature1";
options.pageIndex = 0;
options.bounds = CGRectMake(28, 420, 150, 70);
options.reason = @"I am the owner of the document.";

RemoteSigner *remoteSigner = [[RemoteSigner alloc] init];
remoteSigner.certificateDER = certificateDER;
remoteSigner.chainDER = chainDER;

// signRequest: is called synchronously on the calling thread. Run this on a background queue.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] initWithDocument:document];
    CPDFSignatureCreateResult *result = [workflow signExternalDetachedPKCS7ToPath:signedFilePath options:options signer:remoteSigner];
    if (!result.success) {
        // The errorCode / errorMessage your signer returns appear verbatim in errors.
        for (CPDFValidationReportItem *item in result.errors) {
            NSLog(@"%@: %@", item.code, item.message);
        }
    }
});

Sign with an External Signature Container

When the signing appliance returns a complete detached CMS container, implement the CPDFSignContainer protocol and call signWithContainerToPath:options:container:. Unless you really need to control the container structure, prefer CPDFSignExternal, which lets the SDK build a PAdES-conformant container.

This example shows how to sign with an external signature container:

swift
// Implement CPDFSignContainer when the signing appliance returns a complete CMS container.
class ApplianceContainer: NSObject, CPDFSignContainer {
    func signContainer(with request: CPDFExternalContainerRequest) -> CPDFExternalContainerResult {
        // Send the document digest to the signing appliance and get back a DER-encoded detached CMS SignedData.
        guard let containerDER = MySigningAppliance.container(for: request.documentDigest, digestAlgorithm: request.digestAlgorithm) else {
            return CPDFExternalContainerResult.failureResultWithErrorCode("appliance.failed", errorMessage: "No container returned.")
        }
        return CPDFExternalContainerResult(containerDER: containerDER)
    }
}

DispatchQueue.global(qos: .userInitiated).async {
    let workflow = CPDFSignatureWorkflow(document: document)
    let result = workflow.signWithContainer(toPath: signedFilePath, options: options, container: ApplianceContainer())
    print("Signed: \(result.success)")
}
objective-c
// Implement CPDFSignContainer when the signing appliance returns a complete CMS container.
@interface ApplianceContainer : NSObject <CPDFSignContainer>
@end

@implementation ApplianceContainer

- (CPDFExternalContainerResult *)signContainerWithRequest:(CPDFExternalContainerRequest *)request {
    // Send the document digest to the signing appliance and get back a DER-encoded detached CMS SignedData.
    NSData *containerDER = [MySigningAppliance containerForDigest:request.documentDigest digestAlgorithm:request.digestAlgorithm];
    if (!containerDER) {
        return [CPDFExternalContainerResult failureResultWithErrorCode:@"appliance.failed" errorMessage:@"No container returned."];
    }
    return [CPDFExternalContainerResult resultWithContainerDER:containerDER];
}

@end

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] initWithDocument:document];
    CPDFSignatureCreateResult *result = [workflow signWithContainerToPath:signedFilePath options:options container:[[ApplianceContainer alloc] init]];
    NSLog(@"Signed: %d", result.success);
});

Two-Step Signing

Two-step signing suits cases where signing completes asynchronously, or in another process or on another machine. The steps are as follows:

  1. Prepare: call prepareSignatureToPath:options: to write a PDF with a real ByteRange and an empty /Contents placeholder, and get the digest to sign, documentDigest.

  2. Sign externally: send the digest to whoever holds the private key.

  3. Fill: wrap the signature value in a detached PKCS#7 container with CPDFDetachedPKCS7ContainerOptions, then call fillSignatureAtPath:options: to write it into the placeholder.

Across processes, save the prepared state with exportSessionMetadata or saveSessionMetadataToPath:, and restore it on the filling side with importSessionMetadata: or loadSessionMetadataFromPath:. The session metadata is versioned ASCII text that can be stored in a file or a database, or sent over the network. Do not modify the prepared PDF before it is filled. estimatedContentsSize sets the placeholder size; if the container does not fit, filling fails and you must prepare again.

This example shows the prepare step:

swift
let options = CPDFSignatureCreateOptions()
options.fieldName = "Signature1"
options.pageIndex = 0
options.bounds = CGRect(x: 28, y: 420, width: 150, height: 70)
// Reserve space for the signature container. Increase it for long certificate chains or embedded timestamps.
options.estimatedContentsSize = 16384

DispatchQueue.global(qos: .userInitiated).async {
    let workflow = CPDFSignatureWorkflow(document: document)
    let prepared = workflow.prepareSignature(toPath: preparedPath, options: options)
    guard prepared.success, let info = prepared.preparedSignature else {
        for item in prepared.errors {
            print("\(item.code): \(item.message)")
        }
        return
    }
    // Save the session metadata. Do not modify the PDF at preparedPath until it has been filled.
    _ = info.saveSessionMetadata(toPath: metadataPath)

    // documentDigest is the digest the external key must sign.
    sendToSigner(info.documentDigest)
}
objective-c
CPDFSignatureCreateOptions *options = [[CPDFSignatureCreateOptions alloc] init];
options.fieldName = @"Signature1";
options.pageIndex = 0;
options.bounds = CGRectMake(28, 420, 150, 70);
// Reserve space for the signature container. Increase it for long certificate chains or embedded timestamps.
options.estimatedContentsSize = 16384;

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] initWithDocument:document];
    CPDFPrepareSignatureResult *prepared = [workflow prepareSignatureToPath:preparedPath options:options];
    CPDFPreparedExternalSignatureInfo *info = prepared.preparedSignature;
    if (!prepared.success || !info) {
        for (CPDFValidationReportItem *item in prepared.errors) {
            NSLog(@"%@: %@", item.code, item.message);
        }
        return;
    }
    // Save the session metadata. Do not modify the PDF at preparedPath until it has been filled.
    [info saveSessionMetadataToPath:metadataPath];

    // documentDigest is the digest the external key must sign.
    sendToSigner(info.documentDigest);
});

This example shows the fill step:

swift
DispatchQueue.global(qos: .userInitiated).async {
    // This can run in another process: restore the prepared state from the session metadata.
    let imported = CPDFPreparedExternalSignatureInfo.loadSessionMetadata(fromPath: metadataPath)
    guard imported.success, let info = imported.preparedSignature else {
        print("\(imported.errorCode): \(imported.errorMessage)")
        return
    }

    // Wrap the returned signature value in a detached PKCS#7 container. The digest algorithm must match the prepare step (SHA-256 by default).
    let containerOptions = CPDFDetachedPKCS7ContainerOptions()
    containerOptions.digestAlgorithm = .SHA256
    containerOptions.signerCertificateDER = signerCertificateDER
    containerOptions.certificateChainDER = chainDER
    containerOptions.signatureValue = signatureValue
    containerOptions.signatureAlgorithm = .rsapkcs1v15
    let container = CPDFDetachedPKCS7ContainerOptions.buildDetachedPKCS7Container(with: containerOptions)
    guard container.success else {
        print("\(container.errorCode ?? ""): \(container.errorMessage ?? "")")
        return
    }

    // Fill in the signature container. No open document is needed for this step.
    let fillOptions = CPDFFillSignatureOptions()
    fillOptions.preparedSignature = info
    fillOptions.signatureContents = container.containerDER
    let result = CPDFSignatureWorkflow().fillSignature(atPath: signedFilePath, options: fillOptions)
    print("Signed: \(result.success), output: \(result.outputPath)")
}
objective-c
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    // This can run in another process: restore the prepared state from the session metadata.
    CPDFExternalSigningSessionImportResult *imported = [CPDFPreparedExternalSignatureInfo loadSessionMetadataFromPath:metadataPath];
    if (!imported.success || !imported.preparedSignature) {
        NSLog(@"%@: %@", imported.errorCode, imported.errorMessage);
        return;
    }

    // Wrap the returned signature value in a detached PKCS#7 container. The digest algorithm must match the prepare step (SHA-256 by default).
    CPDFDetachedPKCS7ContainerOptions *containerOptions = [[CPDFDetachedPKCS7ContainerOptions alloc] init];
    containerOptions.digestAlgorithm = CPDFSignatureDigestAlgorithmSHA256;
    containerOptions.signerCertificateDER = signerCertificateDER;
    containerOptions.certificateChainDER = chainDER;
    containerOptions.signatureValue = signatureValue;
    containerOptions.signatureAlgorithm = CPDFExternalSignatureAlgorithmRSAPKCS1v15;
    CPDFExternalContainerResult *container = [CPDFDetachedPKCS7ContainerOptions buildDetachedPKCS7ContainerWithOptions:containerOptions];
    if (!container.success) {
        NSLog(@"%@: %@", container.errorCode, container.errorMessage);
        return;
    }

    // Fill in the signature container. No open document is needed for this step.
    CPDFFillSignatureOptions *fillOptions = [[CPDFFillSignatureOptions alloc] init];
    fillOptions.preparedSignature = imported.preparedSignature;
    fillOptions.signatureContents = container.containerDER;
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] init];
    CPDFFillSignatureResult *result = [workflow fillSignatureAtPath:signedFilePath options:fillOptions];
    NSLog(@"Signed: %d, output: %@", result.success, result.outputPath);
});

Two-Step Signing with In-Memory Data

Since 3.0.2, CPDFDeferredSignSession has accepted and returned PDFs as NSData, without temporary files. Load document from the exact sourceData you pass to the prepare call, with no unsaved changes. Choose the entry point by field type:

  • New signature field: Call prepareWithDocument:sourceData:options:. Set options.digestAlgorithm to choose the digest and options.hashMode to choose what the signer signs. This method places the field but does not create a visible appearance.
  • Existing unsigned signature field: Call prepareDeferredSignForSignatureWidget:sourceData:digestAlgorithm:estimatedContentsSize: on the CPDFDocument that owns the field. Pass the digest algorithm explicitly. This preserves an existing appearance and uses DocumentDigest only.

In 3.2.1, both entry points accept SHA-256, SHA-384 and SHA-512 (SHA-256 is the default for a new field). Other values, including SM3 and Unknown, return sdk.invalid_argument. After a successful prepare, keep preparedData and session unchanged. Do not save the document modified by the prepare call. Give the signer both hashToSign and the result’s digestAlgorithm (SHA256, SHA384 or SHA512). hashToSign is already a binary digest: do not hash it again. The signature value or container you fill must use the same digest algorithm as the prepare call.

hashModeWhat hashToSign containsHow to fill
DocumentDigest (default)The digest of the bytes covered by the PDF’s /ByteRange, equal to documentDigest.Fill with a complete container or a raw signature value. For a raw value, supply the signing certificate at fill time if it was not supplied at prepare time.
SignedAttributes (new field only)The digest of the DER-encoded CMS signed attributes built at prepare time, not documentDigest. Set signerCertificateDER at prepare time.Fill with a raw signature value only. The SDK uses the certificate and attributes from the session and ignores certificates supplied at fill time.

Keep these inputs distinct:

  • Signing identity and certificates: Local private-key signing can use a PKCS#12 (.p12 / .pfx) identity and its password. With an external signer, the private key stays with the signer. Pass one DER-encoded X.509 signing certificate as signerCertificateDER, and one DER certificate per entry in certificateChainDER, not a PKCS#12 file or PEM text.
  • Complete container: Pass DER-encoded detached CMS/PKCS#7 SignedData to fillSession:preparedData:containerDER:verifiesMessageDigest:. Set verifiesMessageDigest to YES: if the container has signed attributes, the SDK compares their messageDigest with the session’s document digest and returns session.message_digest_mismatch on mismatch. Containers without signed attributes skip this check.
  • Raw signature value: Pass binary signature bytes, not a container or Base64 text, to fillSession:preparedData:signatureValue:options:. For RSA, use PKCS#1 v1.5 and a modulus-sized signature; this fill method does not support RSA-PSS. For ECDSA, use a DER-encoded SEQUENCE { r, s }, not concatenated r || s. Decode Base64 responses before filling.