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
Android Guides Two phase signing

Two-Phase Signing ​

When a remote signing service holds the private key, your Android app prepares the PDF and embeds the signature. The service authenticates the signer, authorizes the request, and performs the private-key operation. This guide uses the file-based APIs in Android SDK 3.2.1. Initialize the SDK before starting, and run preparation, embedding, and validation on a worker thread. For local PKCS#12 signing, see Create Digital Signatures.

First, confirm whether your service returns a complete detached CMS (PKCS#7) container or a raw signature value. The main example uses a complete CMS container. When the user confirms the contract, prepare the PDF, persist the session, and submit the digest. Once the service returns the result, embed the signature and validate the output. If your service returns only a raw signature value, use the same workflow with the two changes described below.

For the algorithms, certificate formats, and validation limits of each approach, see Algorithms and Certificate Formats.

Start Signing ​

Save any edits in the reader first. prepare() reloads the PDF from sourcePath and creates a new signature field rather than reusing an existing empty one. This example omits the field rectangle, so the signature is invisible. No signature image appears on the page; verify the result in the report for the new signature field.

requestId is an ID generated by your app. Use separate paths for preparedPath, sessionPath, and outputPath for each request, and do not overwrite the source PDF. Pass the PDF's open password as password, or null if it is not password-protected.

java
String fieldName = "ContractSignature1";
CPDFExternalSignPrepareOptions options = new CPDFExternalSignPrepareOptions()
        .setFieldName(fieldName)
        .setDigestAlgorithm(CPDFExternalSignPrepareOptions.Digest.SHA256)
        .setHashMode(CPDFExternalSignPrepareOptions.HashMode.DocumentDigest);
CPDFExternalSignPrepareResult prepared = CPDFExternalSignSession.prepare(
        sourcePath, preparedPath, password, options);
if (!prepared.isSuccess()) {
    throw new IllegalStateException(prepared.getErrorCode() + ": " + prepared.getErrorMessage());
}

if (!CPDFExternalSignSession.saveSession(sessionPath, prepared.getSession())) {
    throw new IllegalStateException("Cannot save signing session");
}
requests.save(requestId, preparedPath, sessionPath, outputPath, fieldName);
signingService.submit(requestId, prepared.getHashToSign(), prepared.getDigestAlgorithm());

requests and signingService are app-provided interfaces, not SDK APIs. Before submission, requests stores the request ID, file paths, and signature field name. signingService sends the ID, digest, and digest algorithm to your signing service. In DocumentDigest mode, the digest covers the PDF's signed byte ranges. If the service constructs CMS signed attributes, it uses this digest as messageDigest and signs the attributes it constructs. If your API uses Base64, encode only for transport; do not sign the Base64 text.

Use a signature field name that is unique within the document. Keep the prepared PDF byte-for-byte unchanged until the signature is embedded. If the contract changes, prepare it again and submit a new signing request.

Handle the Signing Callback ​

Once your app confirms that signing succeeded, use the callback's requestId to look up the original request. SigningRequest is the record stored by your app; cmsDer contains the complete CMS container bytes returned by the service. Decode a Base64 response before passing it to the SDK. Do not embed a signature if the user cancelled, the service reported a failure, or the request ID does not match a stored record.

java
SigningRequest request = requests.load(requestId);
if (request == null) {
    throw new IllegalStateException("Unknown signing request");
}
String session = CPDFExternalSignSession.loadSession(request.sessionPath);
if (session.isEmpty()) {
    throw new IllegalStateException("Signing session not found");
}
CPDFExternalSignFillResult filled = CPDFExternalSignSession.fillWithContainer(
        session, request.preparedPath, request.outputPath, cmsDer);
if (!filled.isSuccess()) {
    throw new IllegalStateException(filled.getErrorCode() + ": " + filled.getErrorMessage());
}

CPDFDocument signedDocument = new CPDFDocument(context);
try {
    if (signedDocument.open(request.outputPath, password)
            != CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
        throw new IllegalStateException("Cannot open signed PDF");
    }
    CPDFSignatureValidationResult result =
            CPDFSignatureValidator.validate(signedDocument, validationOptions);
    if (result == null) {
        throw new IllegalStateException("No validation result");
    }
    boolean accepted = false;
    for (CPDFSignatureValidationReport report : result.getReports()) {
        if (request.fieldName.equals(report.getFieldName())) {
            accepted = report.getOverallStatus() == CPDFValidationStatus.VALID;
            break;
        }
    }
    if (!result.isSuccess() || !accepted) {
        throw new IllegalStateException("Contract signature did not pass validation");
    }
} finally {
    signedDocument.close();
}

filled.isSuccess() only confirms that the signature was written. Before delivering the PDF, configure validationOptions to match your certificate trust, timestamp, and revocation policies. Confirm that the report for the field created for this request is VALID. A missing report or an INDETERMINATE status does not pass validation. See Verify Digital Signatures for configuration and report details.

If the CMS container is too large for the reserved space, increase the reservation with setEstimatedContentsSize(), prepare the PDF again, and sign the new digest. Do not reuse the original signature.

When the Service Returns a Raw Signature Value ​

  1. When starting the request, use SignedAttributes instead of DocumentDigest and supply the X.509 DER certificate that corresponds to the signing key before calling prepare(). getHashToSign() then returns the digest of the signed attributes. The service must use a prehashed signing API and must not apply SHA-256 again. Raw RSA signatures use PKCS#1 v1.5; RSA-PSS is not supported for this flow.

    java
    options.setHashMode(CPDFExternalSignPrepareOptions.HashMode.SignedAttributes)
            .setSignerCertificateDer(signerCertificateDer);
  2. When handling the callback, replace fillWithContainer() with the call below. signatureValue contains the raw bytes returned by the service. The SDK assembles the CMS container with the certificate and attributes fixed during preparation, so pass null as the last argument. Keep the same result checks and final PDF validation.

    java
    CPDFExternalSignFillResult filled = CPDFExternalSignSession.fillWithSignatureValue(
            session, request.preparedPath, request.outputPath, signatureValue, null);