Media Signing Library

Integrate the DigiCert Media Signing Library with Content Trust Manager to sign media with C2PA Content Credentials.

The DigiCert Content Trust Manager (CTM) Media Signing Library (MSL) lets your application sign media and create C2PA Content Credentials. Use this guide to configure MSL, send signing requests through its ABI 2 interface, and read or verify the resulting assets and manifests.

Version 2.0.0 · C ABI 2 · JSON request schema 1. Applications using ABI 1 must update their bindings before loading this library. See section 3.6 for migration details.

Overview

MSL signs supported media through DigiCert ONE Content Trust Manager and embeds C2PA Content Credentials in the resulting asset, in a detached sidecar, or both.

MSL is implemented in Rust and distributed as a platform-native dynamic library. Applications call its C-compatible interface from Rust, C, C#, Python, Node.js, Go, Java, or another FFI-capable language.

This guide explains the MSL function reference, the JSON request document, standard signing, CAWG identity signing (one-step and two-step), manifest placement (embedded and sidecar), sidecar validation, request metadata, ingredients, custom assertions, result handling, verification, and integration from Rust and widely used backend programming languages.

Supported media types

The following media types are supported by the MSL.

CategorySupported media types
Still imageimage/jpeg, image/png, image/x-adobe-dng, image/heic, image/heif, image/tiff, image/webp,
image/svg+xml, image/gif, image/jxl, image/avif
Videovideo/mp4, video/x-msvideo, video/quicktime
Audioaudio/wav, audio/mp4, audio/flac, audio/mpeg
Documentapplication/pdf - use SIDECAR manifest output
Security: Never embed API keys, credential PINs, or other secrets in source code.

Architecture and integration choices

MSL exposes one operation per task. Every operation takes the same four arguments (a JSON request document, an array of named binary inputs, the input count, and a trace ID) and returns one C2paResult. The request decides whether the asset is a buffer or a file and where the manifest goes, so there are no separate in-memory, path-based, or CAWG variants of each function.

SurfaceBest useResult
c2pa_sign with a path sourceBackend services and large assetsSigned asset written to asset.destination.path; destination_path in the result document
c2pa_sign with an input sourceByte-oriented pipelinesOutput buffer named asset
c2pa_sign with signing.identity.type = CAWG_X509One-step CAWG identity signing with the configured S/MIME credentialSame as standard signing
c2pa_cawg_prepare + c2pa_cawg_completeApplications that produce the CAWG identity signature with their own signerPrepare result document, then the same result as c2pa_sign
c2pa_validate_sidecarChecking a detached Manifest Store against an assetResult document with valid

Prefer path sources for large assets because they avoid copying the complete signed file across the language boundary.

1.1 Platform libraries

Operating systemBinaryTypical path
macOSlibc2pa_rust.dylibrust_binary/libc2pa_rust.dylib
Linuxlibc2pa_rust.sorust_binary/libc2pa_rust.so
Windowsc2pa_rust.dllrust_binary/c2pa_rust.dll

The examples in this guide assume the following project layout:

msl-app/
├── include/c2pa_msl.h
├── input/
├── output/
└── rust_binary/<platform-library>
macOS linking: The macOS binary records an absolute install name from its build machine. Applications that link at build time, including the C and Go examples, can fail at startup with a dyld “image not found” error. Rewrite the library’s install name before building these examples:
install_name_tool -id @rpath/libc2pa_rust.dylib rust_binary/libc2pa_rust.dylib
codesign -f -s - rust_binary/libc2pa_rust.dylib

Applications that load the library by path at runtime—Rust, Python, Node.js, Java and C#—are unaffected by this linking issue.

Prerequisites and configuration

Obtain an account ID, API key, and signing-service URL from the same Content Trust Manager environment:

  • Production: one.digicert.com
  • Demo: demo.one.digicert.com

CAWG identity signing additionally requires an S/MIME credential ID and PIN, supplied through C2PA_SMIME_CREDENTIAL_ID and C2PA_USER_PIN.

Set the following variables before starting the application:

export MSL_ACCOUNT_ID="<account-id>"
export MSL_API_KEY="<api-key>"
export MSL_SIGNING_URL="https://one.digicert.com/documentmanager"
export C2PA_API_KEY="$MSL_API_KEY"
export C2PA_SIGNING_SERVICE_URL="$MSL_SIGNING_URL"
export C2PA_SKIP_SSL_VALIDATION="false"

Use credentials and a signing-service URL from the same environment. Explicitly set C2PA_SKIP_SSL_VALIDATION=false to enable TLS certificate validation.

The examples use MSL_ACCOUNT_ID to populate caller.account_id in each request. MSL_ACCOUNT_ID is an application-level alias, not a native library configuration variable.

2.1 Environment variables

Set the three highlighted variables before starting your application. All other entries are for information purpose only and shall not be altered. The MSL_* variables used by the examples are application-level aliases rather than additional native settings.

Environment variableSet explicitlyDefaultPurpose
C2PA_API_KEYYesNoneAPI key for the signing service. Supply a non-empty key for the account used in the request.
C2PA_SIGNING_SERVICE_URLYesLocal development URLSigning-service endpoint. For production, use https://one.digicert.com/documentmanager or the production URL provided for your environment.
C2PA_SKIP_SSL_VALIDATIONYestrueSet false to validate the signing service’s TLS certificate.
SKIP_C2PA_PUBLIC_TRUST_LIST_CHECKNofalsetrue bypasses public trust-list checks and can allow signing with expired or untrusted credentials. It also relaxes sidecar validation (13). Keep false in production.
C2PA_CLAIM_GENERATOR_NAMENoDigiCert Content Trust ManagerClaim-generator name. Retain the default for DigiCert production signing. The version comes from the library.
C2PA_PRODUCT_NAME, C2PA_PRODUCT_VERSIONNoDigiCert Content Trust Manager; library versionProduct name and version used by the library.
C2PA_SMIME_CREDENTIAL_IDFor CAWGNoneS/MIME credential used for the CAWG identity signature.
C2PA_USER_PINFor CAWGNonePIN for the S/MIME credential.
C2PA_TSA_URLNohttp://timestamp.digicert.comTSA used when signing.tsa_url is absent or blank.
C2PA_TSA_TIMEOUT_SECSNo30Timeout for each TSA request, in seconds. Must be greater than 0.
C2PA_DISABLE_DEFAULT_TSANofalsetrue applies no timestamp when signing.tsa_url is absent or blank. An explicit signing.tsa_url is still used.
C2PA_CAWG_CONTEXT_EXPIRY_SECSNo300Lifetime of a two-step CAWG preparation token, in seconds.
C2PA_VERIFY_TRUSTNotrueEvaluate trust of existing manifests. With false, sidecar validation reports valid rather than trusted.
C2PA_VERIFY_TIMESTAMP_TRUSTNotrueEvaluate trust of timestamps in existing manifests.
C2PA_OCSP_FETCHNofalseFetch OCSP responses for the signing certificate and staple them into the signature.
C2PA_INGREDIENT_OCSP_FETCHNofalseFetch OCSP responses for the manifests of imported ingredients and record them in a c2pa.certificate-status assertion. MSL then calls the ingredient CA’s OCSP responder during signing.
C2PA_REMOTE_MANIFEST_FETCHNotrueAllow resolving remote manifest URLs found in assets. A supplied sidecar is never resolved remotely.
C2PA_SEND_DTM_MSL_HEADERNotrueInclude the library version in the msl-version header. Leave enabled for DigiCert production signing.
C2PA_ENVIRONMENTNoprodEnvironment segment used to derive trust-list URLs from C2PA_TRUST_LIST_BASE_URL.
C2PA_TRUST_LIST_BASE_URL, C2PA_TRUST_LIST_URL, C2PA_TSA_TRUST_LIST_URLNoNoneRemote trust-list locations. An explicit URL wins; otherwise the URLs are <base>/<environment>/C2PA-TRUST-LIST.pem and <base>/<environment>/C2PA-TSA-TRUST-LIST.pem.
C2PA_TRUST_LIST_TTL_SECSNo86400How long a fetched trust list is cached.
C2PA_TRUST_LIST_FAILURE_RETRY_SECSNo300Wait before retrying after a complete trust-list fetch failure.
C2PA_IMAGE_THUMBNAIL_PATH, C2PA_VIDEO_THUMBNAIL_PATH, C2PA_AUDIO_THUMBNAIL_PATH, C2PA_PDF_THUMBNAIL_PATH, C2PA_DOCUMENT_THUMBNAIL_PATHNoBuilt-in thumbnailPath to a file that replaces the built-in thumbnail for that media category. Blank or missing paths are ignored.
C2PA_LOG_LEVELNoinfoLog filter (for example, debug or c2pa=debug). Logs go to standard error, tagged with the trace ID.

Default settings enable certificate and timestamp trust checks, retain the DigiCert claim-generator name, and send the msl-version header required by the signing service. Leave these defaults unchanged for standard production integrations. Changing the defaults may amount to a breach of terms of usage of the Media Signing Library unless specifically confirmed by a DigiCert representative.

2.2 When MSL reads environment variables

MSL reads its environment variables once, when the library is first used in the process, and keeps those values until the process ends.

Set these variables before starting the application. To apply a change, update the startup environment, then restart the process.

The only exception is C2PA_CAWG_CONTEXT_EXPIRY_SECS, which MSL reads on every two-step CAWG call.

Setting variables from code

Python, Node.js, Go and Rust can update the native process environment before loading the library using their respective functions:

LanguageEnvironment-setting interface
Pythonos.environ
Node.jsprocess.env
Goos.Setenv
Ruststd::env::set_var

Java cannot change the environment of a running JVM. In .NET on macOS and Linux, Environment.SetEnvironmentVariable changes only the managed copy.

For Java and C#, export the variables in the shell or service definition that starts the process.

2.3 Python quickstart

Sign an image from Python using the native library and the built-in ctypes module. This walkthrough uses MSL 2.0.0 with ABI 2 and requires no additional Python packages.

Step 1 Download the library

  1. Sign in to DigiCert ONE Content Trust Manager.
  2. Open Client Tool repository.
  3. Download the Media Signing Library package for the application’s operating system and processor architecture.
  4. Keep the accompanying c2pa_msl.h header with the project.

Python loads the binary directly; it does not compile the header.

Operating systemLibrary filename
macOSlibc2pa_rust.dylib
Linuxlibc2pa_rust.so
Windowsc2pa_rust.dll

Step 2 Create the project folders

mkdir msl-python-quickstart
cd msl-python-quickstart
mkdir input
mkdir output
mkdir rust_binary
mkdir include
  • Copy the library into rust_binary/.
  • Copy c2pa_msl.h into include/.
  • Place an unsigned JPEG at input/sample.jpeg.
  • Save the Python program from Step 4 as sign_media.py in the project root.

Step 3 Configure credentials

Set the account ID, API key and signing-service URL in the terminal that will start Python. Use values from the same environment and keep secrets out of source code.

The program maps these aliases to the native library settings and enables TLS certificate validation before loading MSL.

macOS or Linux

export MSL_ACCOUNT_ID="<account-id>"
export MSL_API_KEY="<api-key>"
export MSL_SIGNING_URL="https://one.digicert.com/documentmanager"

Windows PowerShell

$env:MSL_ACCOUNT_ID="<account-id>"
$env:MSL_API_KEY="<api-key>"
$env:MSL_SIGNING_URL="https://one.digicert.com/documentmanager"
Restart the Python process after changing configuration. Settings whose defaults meet your requirements do not need to be exported.

Step 4 Create the Python program

Create sign_media.py in the project root.

The program checks ABI compatibility, signs input/sample.jpeg to a new destination, reads the versioned result document, and releases the native result exactly once.

import ctypes
import json
import os
import platform
from pathlib import Path


class C2paInput(ctypes.Structure):
    _fields_ = [
        ("name", ctypes.c_char_p),
        ("data", ctypes.c_void_p),
        ("len", ctypes.c_size_t),
    ]


class C2paOutput(ctypes.Structure):
    _fields_ = [
        ("name", ctypes.c_void_p),
        ("data", ctypes.c_void_p),
        ("len", ctypes.c_size_t),
    ]


class C2paResult(ctypes.Structure):
    _fields_ = [
        ("error_code", ctypes.c_int32),
        ("error_message", ctypes.c_void_p),
        ("result_json", ctypes.c_void_p),
        ("outputs", ctypes.POINTER(C2paOutput)),
        ("output_count", ctypes.c_size_t),
    ]


# Set native configuration before loading the library.
required = ("MSL_ACCOUNT_ID", "MSL_API_KEY", "MSL_SIGNING_URL")
for name in required:
    if not os.environ.get(name, "").strip():
        raise SystemExit(f"Set {name} before running this program")

os.environ["C2PA_API_KEY"] = os.environ["MSL_API_KEY"]
os.environ["C2PA_SIGNING_SERVICE_URL"] = os.environ["MSL_SIGNING_URL"]
os.environ["C2PA_SKIP_SSL_VALIDATION"] = "false"

root = Path(__file__).resolve().parent
source = root / "input" / "sample.jpeg"
destination = root / "output" / "sample_signed.jpeg"
if not source.is_file():
    raise SystemExit(f"Input file not found: {source}")
if destination.exists():
    raise SystemExit("Output already exists; choose a new destination")
destination.parent.mkdir(parents=True, exist_ok=True)

library_name = {
    "Darwin": "libc2pa_rust.dylib",
    "Linux": "libc2pa_rust.so",
    "Windows": "c2pa_rust.dll",
}.get(platform.system())
if library_name is None:
    raise SystemExit("Unsupported operating system")
library_path = root / "rust_binary" / library_name
library = ctypes.CDLL(str(library_path))

abi_version = library.c2pa_abi_version
abi_version.argtypes = []
abi_version.restype = ctypes.c_uint32
if abi_version() != 2:
    raise SystemExit("This example requires MSL ABI 2")

sign = library.c2pa_sign
sign.argtypes = [
    ctypes.c_char_p,
    ctypes.POINTER(C2paInput),
    ctypes.c_size_t,
    ctypes.c_char_p,
]
sign.restype = ctypes.POINTER(C2paResult)
free_result = library.c2pa_free_result
free_result.argtypes = [ctypes.POINTER(C2paResult)]
free_result.restype = None

request = {
    "schema_version": 1,
    "caller": {"account_id": os.environ["MSL_ACCOUNT_ID"]},
    "asset": {
        "filename": source.name,
        "source": {"path": str(source)},
        "destination": {"path": str(destination)},
    },
    "signing": {"manifest_output": "EMBEDDED", "roles": ["creator"]},
}

pointer = sign(json.dumps(request).encode("utf-8"), None, 0, None)
if not pointer:
    raise RuntimeError("MSL returned a null result pointer")
try:
    result = pointer.contents
    if result.error_code:
        message = (
            ctypes.string_at(result.error_message).decode("utf-8")
            if result.error_message else "Unknown signing error"
        )
        raise RuntimeError(f"{result.error_code}: {message}")
    document = json.loads(
        ctypes.string_at(result.result_json).decode("utf-8")
    )
    print("Signed file:", document["destination_path"])
    print("Signing reference:", document["manifest_id"])
finally:
    free_result(pointer)

Step 5 Sign the image

Run the program from the project root. The destination output/sample_signed.jpeg must not already exist.

python3 sign_media.py

On Windows, use python sign_media.py if python is the configured interpreter.

The program prints the signed-file path and the signing reference.

Step 6 Verify the signed image

Install c2patool separately, then inspect the signed image with signer trust enabled:

c2patool -d output/sample_signed.jpeg trust --trust_anchors=https://raw.githubusercontent.com/c2pa-org/conformance-public/refs/heads/main/trust-list/C2PA-TRUST-LIST.pem

Check the active manifest, claim signature, asset binding and current failure results. A trusted signer is reported with validation_state=Trusted.

Use the reader’s active_manifest label to select a claim. The signing reference printed by the program is a separate identifier.

MSL function reference

MSL exports the following C-compatible functions. All strings are null-terminated UTF-8 (const char *). Every returned C2paResult * is allocated by MSL and must be released exactly once with c2pa_free_result. Do not read result fields after releasing them.

ABI break: Version 2 removes every ABI 1 export (c2pa_sign_content*, c2pa_sign_content_with_cawg_identity*, c2pa_prepare_cawg_signing*, c2pa_complete_cawg_signing*, c2pa_free_prepare_result, c2pa_free_string, and the positional c2pa_validate_sidecar) together with the C2paSignedResult and C2paPrepareResult structures. Calling the new library with the previous argument lists or result layouts is undefined behaviour. Update headers, ctypes, Koffi, cgo, JNA, and P/Invoke declarations, then rebuild callers before deploying this library.

3.1 Functions

FunctionPurposeReturns
c2pa_abi_versionReports the ABI version (2). Never allocates.uint32_t
c2pa_library_infoReports ABI version, supported request schema versions, and library version.C2paResult * with result_json
c2pa_signStandard signing and one-step CAWG identity signing, from a buffer or a file.C2paResult *; asset output or destination_path; sidecar output when requested
c2pa_cawg_prepareStep 1 of two-step CAWG signing.C2paResult * with the preparation token and hash to sign
c2pa_cawg_completeStep 2 of two-step CAWG signing.Same as c2pa_sign
c2pa_validate_sidecarChecks a detached Manifest Store against an asset.C2paResult * with valid
c2pa_free_resultReleases a result and everything it owns. Safe to call with NULL.void

3.2 C declarations include c2pa_msl h

Declare the structures and functions as follows. Field and parameter order are part of the binary interface.

#ifndef C2PA_MSL_H
#define C2PA_MSL_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define C2PA_ABI_VERSION 2
typedef struct {
    const char    *name;   /* referenced from request_json, e.g. "asset" */
    const uint8_t *data;   /* may be NULL only when len == 0 */
    size_t         len;
} C2paInput;
typedef struct {
    char    *name;         /* e.g. "asset", "sidecar" */
    uint8_t *data;         /* NULL when len == 0 */
    size_t   len;
} C2paOutput;
typedef struct {
    int32_t     error_code;     /* 0 = success, otherwise a C2paErrorCode value */
    char       *error_message;  /* NULL on success */
    char       *result_json;    /* NULL on error; the versioned result document */
    C2paOutput *outputs;        /* NULL when output_count == 0 */
    size_t      output_count;
} C2paResult;
uint32_t    c2pa_abi_version(void);
C2paResult *c2pa_library_info(void);
C2paResult *c2pa_sign(const char *request_json, const C2paInput *inputs,
                      size_t input_count, const char *trace_id);
C2paResult *c2pa_cawg_prepare(const char *request_json, const C2paInput *inputs,
                              size_t input_count, const char *trace_id);
C2paResult *c2pa_cawg_complete(const char *request_json, const C2paInput *inputs,
                               size_t input_count, const char *trace_id);
C2paResult *c2pa_validate_sidecar(const char *request_json, const C2paInput *inputs,
                                  size_t input_count, const char *trace_id);
void c2pa_free_result(C2paResult *result);
#ifdef __cplusplus
}
#endif
#endif /* C2PA_MSL_H */

3.3 Rules shared by every operation

  • Version check. Compare c2pa_abi_version() with the version you were built against before calling anything else, and refuse to run on a mismatch. A mismatched struct layout or signature is undefined behaviour, not an error.

  • Ownership. c2pa_free_result frees the strings, the outputs array, and every output buffer. Do not free any of them separately. Input buffers stay owned by the caller and are only read during the call.

  • request_json. Must be non-NULL, UTF-8, at most 8 MiB, and a JSON object whose schema_version is 1. Unknown fields are rejected at every level, so a typo fails instead of being ignored. Optional fields may be omitted or null. A blank caller.user_id or signing.tsa_url is treated as absent.

  • Inputs. inputs may be NULL only when input_count is 0. Every input needs a non-empty, unique, UTF-8 name; data may be NULL only when len is 0. Every input must be referenced by the request, and every reference must name a supplied input.

  • Sources. A binary value is referenced as {"input": "<input name>"} or, where supported, {"path": "/absolute/path"}. Each field below states which forms it accepts.

  • Results. On success error_code is 0, error_message is NULL, and result_json holds the result document with "schema_version": 1. On failure error_code is non-zero, error_message explains why, and result_json and outputs are NULL.

  • Trace ID. See 4.9.

  • Stability. New options are added as optional request fields and new binary artifacts as new output names, so neither changes a signature or a struct layout. C2PA_ABI_VERSION changes only if a signature or layout ever has to.

3.4 Result structure

FieldTypeDescription
error_codeint32_t0 on success. An error code from 3.5 on failure.
error_messagechar *NULL on success. Human-readable message on failure.
result_jsonchar *NULL on failure. The versioned result document on success (see 4.10 and 13).
outputsC2paOutput *Binary artifacts, looked up by name. NULL when output_count is 0.
output_countsize_tNumber of entries in outputs.

Output names: asset is the signed asset when the request used an input source (always present, may be empty); sidecar is the detached Manifest Store when the placement includes a sidecar. c2pa_library_info, c2pa_cawg_prepare, and c2pa_validate_sidecar return no outputs.

3.5 Error codes

CodeNameMeaning
0SUCCESSThe operation completed.
4000INVALID_PARAMETERMalformed request, unknown field, bad input, or rejected value.
4001INVALID_ROLEA role is not one of the supported roles for the requested identity type.
4002INVALID_ENCODINGA string is not valid UTF-8.
4003VALIDATION_FAILEDManifest or certificate validation prevented signing, for example the asset’s existing manifest failed validation or the S/MIME certificate has no Organization (O) field.
4029RATE_LIMITEDThe signing service rejected the call with HTTP 429.
5000INTERNAL_ERRORUnexpected failure, including a caught panic.
5001CONFIGURATION_ERRORMissing or invalid library configuration, such as no API key.
5020SIGNING_SERVICE_ERRORThe signing service returned an error or was unreachable.
5021CERTIFICATE_FETCH_ERRORThe signing certificate could not be fetched.
5022SIGNING_FAILEDThe manifest could not be signed, for example the destination exists or a CAWG signature did not verify.

3.6 Migrating from ABI 1

Each ABI 2 request is translated into exactly the values the ABI 1 exports passed to the signing engine, so signing behaviour is unchanged. The observable differences come from the document shape: unknown fields are rejected, an action label can be listed more than once, and the request is capped at 8 MiB. Validation messages raised by the signing engine can still name a field by its ABI 1 name (for example ingredientPaths); the meaning matches the corresponding request field.

ABI 1ABI 2
c2pa_sign_content, c2pa_sign_content_from_pathc2pa_sign with asset.source = input / path
c2pa_sign_content_with_cawg_identity, c2pa_sign_content_with_cawg_identity_from_pathc2pa_sign with signing.identity.type = CAWG_X509
c2pa_prepare_cawg_signing, c2pa_prepare_cawg_signing_from_pathc2pa_cawg_prepare
c2pa_complete_cawg_signing, c2pa_complete_cawg_signing_from_pathc2pa_cawg_complete
c2pa_validate_sidecar(asset, …, sidecar, …)c2pa_validate_sidecar with a request document
C2paSignedResult, C2paPrepareResult, C2paSidecarValidationResultC2paResult
c2pa_free_prepare_result, c2pa_free_sidecar_validation_resultc2pa_free_result
file_data / file_data_len, input_path, output_pathasset.source, asset.destination
filename, account_id, user_id, tsa_urlasset.filename, caller.account_id, caller.user_id, signing.tsa_url
roles_csvsigning.roles (array)
requested_output_mode (1 / 2 / 3)signing.manifest_output (EMBEDDED / SIDECAR / BOTH)
previous_sidecar_data / previous_sidecar_data_lenprovenance.previous_sidecar
cawg_certificate_chain_pem, hard_binding_hash_b64signing.identity (CAWG_X509_EXTERNAL)
additional_actions_jsonprovenance.actions: an ordered list. The label-keyed map and the software, version, and time aliases are gone; use software_agent and when.
signing_metadata_json.isNewCreation, digitalSourceType, createdWithAiprovenance.new_creation, digital_source_type, created_with_ai
signing_metadata_json.softwareAgent, softwareVersionprovenance.ai_generator.name, provenance.ai_generator.version
signing_metadata_json.editedWithAiRemoved; the library now rejects it. Declare AI editing with an action that carries digital_source_type (for example, compositeWithTrainedAlgorithmicMedia).
signing_metadata_json.initialActionprovenance.initial_action (softwareAgent → software_agent, ingredientPaths → ingredient IDs in ingredients)
signing_metadata_json.ingredientsprovenance.ingredients (path → source.path)
signing_metadata_json.aiDisclosureassertions.ai_disclosure (camelCase → snake_case; scientificDomain → scientific_domains; humanOversightLevel → human_oversight_level)
aiInference + aiInferenceConstraintsInfo (and the other three)assertions.usage_rights.<kind>.permission / assertions.usage_rights.<kind>.constraints_info
signing_metadata_json.includeExifMetadataassertions.exif.extract_from_asset
custom_assertions_jsonassertions.custom
trace_idtrace_id (unchanged)
Result manifest_json (string)Removed. Read the signed asset or returned sidecar with a C2PA reader. Use the reader’s active_manifest value to select the active claim; do not use result.manifest_id for that lookup.
Result ingredient_diagnostics_json (string)ingredients (JSON array in the result document)
Result output_pathdestination_path
Result signed_data, signed_data_len, sidecar_dataOutputs asset and sidecar

The request document

Every operation except c2pa_cawg_complete takes a request document with the same top-level shape. The following request sets every field to show its shape; not every combination is meaningful.

{
  "schema_version": 1,
  "caller":  { "account_id": "…", "user_id": "…" },
  "asset":   { "filename": "photo.jpg",
               "source": { "path": "/data/in/photo.jpg" },
               "destination": { "path": "/data/out/photo.jpg" } },
  "signing": { "manifest_output": "EMBEDDED",
               "roles": ["creator", "publisher"],
               "tsa_url": "http://timestamp.digicert.com",
               "identity": { "type": "NONE" } },
  "provenance": {
    "previous_sidecar": { "input": "previous_sidecar" },
    "new_creation": true,
    "digital_source_type": "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation",
    "created_with_ai": false,
    "ai_generator": { "name": "ImageGen", "version": "3.1" },
    "initial_action": { … },
    "ingredients": [ … ],
    "actions": [ … ]
  },
  "assertions": {
    "ai_disclosure": { … },
    "usage_rights": { … },
    "exif": { "extract_from_asset": true },
    "custom": [ … ]
  }
}
FieldRequiredMeaning
caller.account_idYesAccount the signature is made for.
caller.user_idNoUser within the account. When absent, the API key’s context is used.
asset.filenameYesName used for media-type detection and as the manifest title.
asset.sourceYes{“input”: …} signs bytes and returns the asset output. {“path”: …} signs a file.
asset.destination.pathPath source onlyWhere the signed asset is written. Must be absent for an input source. Use a path that does not exist yet; an existing file fails with 5022.
signing.manifest_outputYesEMBEDDED, SIDECAR, or BOTH. See 4.2.
signing.rolesYesNon-empty list of roles. See 4.1.
signing.tsa_urlNoTimestamp authority. Absent or blank uses C2PA_TSA_URL (or no timestamp when C2PA_DISABLE_DEFAULT_TSA is true). For two-step signing, set it in the prepare call.
signing.identity.typeNoNONE (default): standard signing. CAWG_X509: add a CAWG identity assertion signed with the configured S/MIME credential. CAWG_X509_EXTERNAL: valid only for c2pa_cawg_prepare. See 12.
provenance.*NoOrigin and processing history. See 4.3 to 4.7.
assertions.*NoAssertions added to the manifest. See 4.4 to 4.8.

Omit provenance and assertions (or set them to null) when there is nothing to declare.

4.1 Standard roles

signing.roles is a non-empty list. Values are trimmed, matched case-insensitively, and de-duplicated; blank entries are skipped. With identity NONE, only the Dublin Core roles creator, contributor, and publisher are accepted, and MSL writes them into cawg.metadata. Any other value, including CAWG-only roles such as editor, fails with 4001. A role that contains a comma fails with 4000. CAWG identity roles are listed in 12.2.

4.2 Manifest placement

signing.manifest_output selects where the Manifest Store goes. provenance.previous_sidecar carries a previously issued store forward. The two-step CAWG flow takes both at prepare; complete takes neither.

signing.manifest_outputSigned assetsidecar output
EMBEDDEDManifest Store embeddedAbsent
SIDECARUnmodifiedDetached Manifest Store (a .c2pa payload)
BOTHManifest Store embeddedThe same store, also detached
  • Any other value fails with 4000.

  • SIDECAR is rejected for an asset that already carries an embedded manifest, because it would discard that provenance. Request EMBEDDED or BOTH instead.

  • Read actual_placement and asset_modified_from_input in the result rather than assuming the request was honoured.

  • SIDECAR output leaves the asset bytes unchanged and returns a detached Manifest Store. MSL binds the store to the asset so that the sidecar can be validated against the original file.

  • Path sources always write the asset to asset.destination.path (in SIDECAR mode, a byte-identical copy of the input) and return the detached store as the sidecar output. Persist it as <asset stem>.c2pa if needed.

  • provenance.previous_sidecar ({"input": "<name>"}) is the Manifest Store issued for a previous signing of the same asset. It becomes the parent ingredient and carries the provenance chain forward for an asset that holds nothing embedded. It must bind to the supplied asset: a store issued for different bytes is rejected. Omit the field when absent.

4.3 Provenance and signing metadata

FieldTypeDescription
provenance.new_creationbooleanAsserts the asset is a new creation (c2pa.created). Ignored when the asset already has provenance. Existing provenance, a previous sidecar, or an explicit parentOf ingredient always produces c2pa.opened.
provenance.digital_source_typestringIPTC / C2PA digital source type URI for the first action (see the table below). Overridden by created_with_ai = true.
provenance.created_with_aibooleanThe asset was created with AI (new assets only). Results in trainedAlgorithmicMedia.
provenance.ai_generatorobjectname and version of the software used for AI-assisted creation. Used only when created_with_ai is true.
provenance.initial_actionobjectMetadata for the first action. See 4.5.
provenance.ingredients[]arraySource files recorded as C2PA ingredients. See 4.6.
provenance.actions[]arrayProcessing actions. See 4.4.
assertions.exif.extract_from_assetbooleanCopy supported EXIF fields into the gathered c2pa.metadata assertion. Only fields present in the input are copied. Values are normalized; for example, ColorSpace 1 becomes sRGB.
assertions.usage_rights.ai_inferenceobjectpermission: allowed, prohibited or constrained. Supply a non-empty constraints_info only when permission is constrained; omit it for other values.
assertions.usage_rights.generative_ai_trainingobjectSame shape.
assertions.usage_rights.data_mining_and_analyticsobjectSame shape.
assertions.usage_rights.non_generative_ai_trainingobjectSame shape.
assertions.ai_disclosureobjectc2pa.ai-disclosure assertion. See 4.7.
assertions.custom[]arrayCaller-defined assertions. See 4.8.

created_with_ai for a new asset results in the trainedAlgorithmicMedia digital source type. To record AI editing of an existing asset, declare an action (for example c2pa.edited) with digital_source_type set to compositeWithTrainedAlgorithmicMedia.

Use one of the following digital_source_type values at the provenance level or on an additional action. The value must describe how the content was created or processed. Values outside this vocabulary are rejected with 4000.

ValueDescription
http://cv.iptc.org/newscodes/digitalsourcetype/digitalCaptureDigital capture
http://cv.iptc.org/newscodes/digitalsourcetype/computationalCaptureComputational capture
http://cv.iptc.org/newscodes/digitalsourcetype/negativeFilmNegative film
http://cv.iptc.org/newscodes/digitalsourcetype/positiveFilmPositive film
http://cv.iptc.org/newscodes/digitalsourcetype/printPrint
http://cv.iptc.org/newscodes/digitalsourcetype/humanEditsHuman edits
http://cv.iptc.org/newscodes/digitalsourcetype/algorithmicallyEnhancedAlgorithmically enhanced
http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreationDigital creation
http://cv.iptc.org/newscodes/digitalsourcetype/dataDrivenMediaData-driven media
http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMediaTrained algorithmic media
http://cv.iptc.org/newscodes/digitalsourcetype/algorithmicMediaAlgorithmic media
http://cv.iptc.org/newscodes/digitalsourcetype/screenCaptureScreen capture
http://cv.iptc.org/newscodes/digitalsourcetype/virtualRecordingVirtual recording
http://cv.iptc.org/newscodes/digitalsourcetype/compositeComposite
http://cv.iptc.org/newscodes/digitalsourcetype/compositeCaptureComposite capture
http://cv.iptc.org/newscodes/digitalsourcetype/compositeSyntheticComposite synthetic
http://cv.iptc.org/newscodes/digitalsourcetype/compositeWithTrainedAlgorithmicMediaComposite with trained algorithmic media
http://c2pa.org/digitalsourcetype/emptyEmpty (C2PA)
http://c2pa.org/digitalsourcetype/trainedAlgorithmicDataTrained algorithmic data (C2PA)

MSL writes usage permissions to cawg.training-mining. Request values allowed, prohibited and constrained become use=allowed, use=notAllowed and use=constrained respectively. For constrained, constraints_info is written as constraint_info. The request categories map to cawg.ai_inference, cawg.ai_generative_training, cawg.data_mining and cawg.non_generative_ai_training. This metadata assertion does not add a CAWG identity assertion.

EXIF extraction copies supported tags that are present in the input file. Use a file with an EXIF subIFD containing the properties you want to retain, such as DateTimeOriginal, ExposureTime, ExifVersion, ColorSpace and FNumber. Values are normalized in c2pa.metadata; for example, ColorSpace 1 is represented as sRGB.

4.4 Additional actions

provenance.actions is an optional ordered list of caller-declared actions. Order is preserved and a label can appear more than once. Omit it, or pass [], to declare none. The ABI 1 label-keyed action map is no longer accepted.

{
  "provenance": {
    "actions": [
      { "action": "c2pa.edited", "description": "First edit" },
      { "action": "c2pa.resized" },
      { "action": "c2pa.edited", "description": "Final edit" },
      { "action": "c2pa.translated",
        "parameters": { "source_language": "en-US", "target_language": "fr-FR" } }
    ]
  }
}

Action fields

FieldTypeRequirementDescription
actionstringRequiredAction label.
descriptionstringOptionalDescription of the action, up to 4096 characters.
whenstringOptionalEvent time in RFC 3339 format with a time zone, for example 2026-08-21T06:00:00Z. Defaults to the time MSL processes the request. This is a caller-declared time, not a trusted timestamp.
software_agentobjectOptionalSoftware that performed the action: name (required, non-blank), version, and operating_system.
digital_source_typestringOptionalAccepted digital source type URI for this action (see 4.3).
ingredientsarray of stringsConditionalIDs declared in provenance.ingredients. Links the action to those ingredients. Required for c2pa.mixed and c2pa.removed.
parameters.source_language, parameters.target_languagestringConditionalValid BCP 47 language tags. Required for c2pa.translated; rejected on other actions.

Unknown fields, wrong types, and invalid values fail with 4000.

Action labels

CategoryLabelsRule
Declarablec2pa.edited, c2pa.resized, c2pa.filtered, c2pa.converted, c2pa.cropped, c2pa.transcoded, c2pa.trimmed, c2pa.addedText, c2pa.adjustedColor, c2pa.changedSpeed, c2pa.deleted, c2pa.drawing, c2pa.dubbed, c2pa.edited.metadata, c2pa.enhanced, c2pa.mastered, c2pa.orientation, c2pa.published, c2pa.remixed, c2pa.repackaged, c2pa.resized.proportional, c2pa.unknownAccepted.
Conditionalc2pa.translatedRequires parameters.source_language and parameters.target_language.
Conditionalc2pa.mixedRequires ingredients that select audio componentOf ingredients.
Conditionalc2pa.removedRequires ingredients that select componentOf ingredients with a resolvable manifest.
Managed by MSLc2pa.created, c2pa.opened, c2pa.placedRejected if supplied. MSL selects c2pa.created or c2pa.opened from the asset’s provenance and new_creation, and adds one grouped c2pa.placed action for all componentOf ingredients.
Not supportedc2pa.redacted, c2pa.watermarked.bound, c2pa.watermarked.unboundRejected.
Deprecatedc2pa.color_adjustments, c2pa.watermarked, c2pa.copied, c2pa.formatted, c2pa.version_updated, c2pa.printed, c2pa.managed, c2pa.produced, c2pa.savedRejected. C2PA 2.4 no longer allows these labels to be written.
Not enabledfont.charactersAdded, font.charactersDeleted, font.charactersModified, font.createdFromVariableFont, font.edited, font.hinted, font.merged, font.openTypeFeatureAdded, font.openTypeFeatureModified, font.openTypeFeatureRemoved, font.subsetRejected until font-asset signing is supported.
UnknownAny other labelRejected.
  • allActionsIncluded is always emitted. On the c2pa.opened path it is always true. On the c2pa.created path it is true when at least one additional action is provided (or created_with_ai adds an AI-related action) and false otherwise.

  • Every signing path re-checks the assembled manifest immediately before signing and aborts with VALIDATION_FAILED rather than produce a non-conformant manifest (every c2pa.actions* assertion must carry a boolean allActionsIncluded; when the only action is c2pa.opened, the flag must be true).

  • MSL no longer restricts which ingredients a c2pa.transcoded action may reference. The bundled c2pa-rs 0.90.21 reports assertion.action.ingredientMismatch for a transcoded action that references a non-parentOf ingredient; verify the output before relying on that combination.

4.5 Initial action metadata

provenance.initial_action adds metadata to the first action. MSL selects that action: c2pa.created for new content, or c2pa.opened when the asset already has C2PA provenance (including a previous sidecar) or an explicit parentOf ingredient is included. initial_action cannot change the action type, and new_creation does not override existing provenance.

{
  "provenance": {
    "new_creation": true,
    "digital_source_type":
      "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation",
    "initial_action": {
      "description": "Created a new asset from the selected sources",
      "when": "2026-08-21T11:25:00+05:30",
      "software_agent": { "name": "Client Editor", "version": "2.0",
                          "operating_system": "Windows 11" },
      "ingredients": ["source-a", "source-b"]
    },
    "ingredients": [
      { "id": "source-a", "source": { "path": "/trusted/source-a.jpg" }, "relationship": "inputTo" },
      { "id": "source-b", "source": { "path": "/trusted/source-b.jpg" }, "relationship": "inputTo" }
    ]
  }
}
  • All four fields are optional. Unknown keys and wrong types fail with 4000.

  • ingredients can reference only ids declared in provenance.ingredients. For c2pa.opened, omit it or select only the explicit parentOf ingredient.

  • parameters (including languages) are not accepted in initial_action.

  • when is a caller-declared event time, not a trusted timestamp.

4.6 Ingredients

provenance.ingredients records the source files that a derived or composite asset was made from. Each entry becomes a c2pa.ingredient.v3 assertion. c2pa_sign and c2pa_cawg_prepare accept it for every asset type and source.

{
  "provenance": {
    "ingredients": [
      { "source": { "path": "/data/msl/jobs/42/original.jpeg" } },
      { "id": "logo",   "source": { "path": "/data/msl/jobs/42/logo.png" },   "relationship": "componentOf" },
      { "id": "prompt", "source": { "path": "/data/msl/jobs/42/prompt.txt" }, "relationship": "inputTo" }
    ]
  }
}
FieldTypeRequirementDescription
sourceobjectRequired{"path": "<absolute path>"} on the host running MSL. {"input": …} is not accepted. Relative or empty paths, paths with NUL characters, and overlong paths are rejected.
relationshipstringOptionalparentOf (default), componentOf, or inputTo.
idstringOptionalUnique, non-blank name that initial_action.ingredients and actions[].ingredients use to select this ingredient.
  • Omitting ingredients, null, and [] are equivalent.

  • Declare at most one parentOf ingredient; remember that parentOf is the default. If the asset being signed already has C2PA provenance, declare ingredients as componentOf or inputTo.

  • Each ingredient must be a readable regular file with an absolute path and a size no greater than 512 MiB. Use distinct canonical paths and keep the files unchanged for the duration of the call. Validate inputs before signing and stop processing when MSL returns an error.

  • Signed ingredients are included with their manifest store. Unsigned files and formats C2PA cannot read are included with their hash only. A parseable manifest that fails validation is still included, and its validation codes are reported.

  • MSL records the SHA-256 of each file in the ingredient metadata as com.digicert.msl.ingredientHash.

  • componentOf ingredients are referenced by one c2pa.placed action that MSL adds. inputTo ingredients get no automatic action.

  • When the unsigned target is its only ingredient, set new_creation=false. MSL records the target as parentOf and selects c2pa.opened. Setting new_creation=true in that request returns 4000. The target must not appear alongside other ingredients.

  • With C2PA_INGREDIENT_OCSP_FETCH=true, OCSP is fetched once per signed ingredient.

Security: MSL opens ingredient paths with the privileges of the process that hosts it. Pass only paths from locations your application controls; never pass raw paths supplied by end users. MSL does not limit the number of ingredients (only 512 MiB per file), so enforce your own request-size, count, aggregate-byte, concurrency, and time limits. Error and success behaviour can act as a limited path-existence oracle, and the signed output reveals each included file’s SHA-256, manifest store, and any thumbnail.

Ingredient diagnostics

When ingredients are requested, the result document’s ingredients array contains one entry per ingredient, in request order. It is absent when no ingredients were requested, and a failed call has no result document.

[
  { "path": "/data/msl/jobs/42/original.jpeg", "status": "included", "included": true,
    "relationship": "parentOf", "sha256": "9f2c…",
    "message": "Ingredient included with its C2PA manifest store." },
  { "path": "/data/msl/jobs/42/tampered.jpg", "status": "invalid_manifest", "included": true,
    "relationship": "inputTo", "sha256": "41d0…",
    "message": "Ingredient manifest was included with C2PA validation failures recorded.",
    "validation_codes": ["assertion.dataHash.mismatch"] }
]
statusincludedMeaning
includedtrueIncluded with its C2PA manifest store. validation_codes is present if reported.
unsignedtrueThe file has no C2PA manifest. Included with its hash only.
unsupported_formattrueC2PA cannot read this format. Included with its hash only.
invalid_manifesttrueThe manifest was parsed but failed validation. Included, with validation_codes.

Each entry also has path, relationship, sha256 (lowercase hexadecimal; omitted when the file could not be read), and message. Files that are missing, inaccessible, or too large do not produce an entry because they abort the whole request.

SituationResult
More than one parentOf entry (remember the default)Rejected (4000)
Target already has C2PA provenance and a different explicit parentOf is suppliedRejected; declare it componentOf or inputTo
Target has no provenance and an explicit parentOf is includedIt replaces the implicit self-parent; the first action is c2pa.opened
Unsigned target is its only ingredientSet new_creation=false for parentOf / c2pa.opened. new_creation=true returns 4000.
Target is its only ingredient and previous_sidecar is suppliedThe matching sidecar supplies the parent manifest. A sidecar for different asset bytes returns 4003.
Self-reference plus any other ingredientRejected: the file being signed has itself as an ingredient along with other ingredients

4.7 AI disclosure assertion

The c2pa.ai-disclosure assertion records structured information about the AI model used to create or modify the signed asset. It is embedded in the manifest when assertions.ai_disclosure is present. Including it is optional; if you include it, model_type is required and every other field is optional.

FieldRequirementAccepted values
model_typeRequired when ai_disclosure is presentOne of the C2PA 2.4 model-type values: c2pa.types.model, c2pa.types.model.caffe, c2pa.types.model.caffe2, c2pa.types.model.catboost, c2pa.types.model.coreml, c2pa.types.model.flax, c2pa.types.model.huggingface.transformers, c2pa.types.model.jax, c2pa.types.model.keras, c2pa.types.model.lightgbm, c2pa.types.model.ml_net, c2pa.types.model.mxnet, c2pa.types.model.onnx, c2pa.types.model.openvino, c2pa.types.model.openvino.parameter, c2pa.types.model.openvino.topology, c2pa.types.model.paddle, c2pa.types.model.pytorch, c2pa.types.model.sklearn, c2pa.types.model.tensorflow, c2pa.types.model.tensorrt, c2pa.types.model.tflite, c2pa.types.model.torchscript, c2pa.types.model.xgboost
model_nameOptionalAny free-text string, for example Acme Creative Studio v3.2.
model_identifierOptionalAny string that uniquely identifies the model: a URI, PURL, UUID, or other identifier.
content_profile.human_oversight_levelOptionalfully_autonomous, prompt_guided, or human_validated.
scientific_domainsOptionalA non-empty array of arXiv category identifiers, for example cs.AI, cs.CV, cs.CL, cs.LG.
metadataOptionalAn arbitrary JSON object. Nested objects are supported; arrays and primitive values are rejected.
human_oversight_levelMeaning
fully_autonomousThe AI model produced the content without human review.
prompt_guidedA human provided prompts or direction, but did not review the output.
human_validatedA human reviewed and approved the AI-generated output.

Minimal ai_disclosure model_type only

{
  "provenance": { "new_creation": true, "created_with_ai": true },
  "assertions": { "ai_disclosure": { "model_type": "c2pa.types.model" } }
}

Complete ai_disclosure all fields

{
  "assertions": {
    "ai_disclosure": {
      "model_type": "c2pa.types.model",
      "model_name": "Acme Creative Studio v3.2",
      "model_identifier": "https://ai.acme.com/models/creative-studio/v3.2",
      "content_profile": { "human_oversight_level": "human_validated" },
      "scientific_domains": ["cs.CV", "cs.LG"],
      "metadata": { "provider": "Acme", "workflow": { "name": "poster", "version": 3 } }
    }
  }
}

MSL records this as a c2pa.ai-disclosure assertion in the manifest, using the C2PA field names (modelType, modelName, modelIdentifier, contentProfile.humanOversightLevel, scientificDomain, metadata).

4.8 Custom assertions

assertions.custom adds caller-defined assertions to the manifest. c2pa_sign and c2pa_cawg_prepare accept it; c2pa_cawg_complete does not, because the assertions are captured at prepare time. Omit it, or pass null or [], when there are none.

{
  "assertions": {
    "custom": [
      { "label": "com.example.asset-info.v1",
        "data": { "assetId": "42844", "campaign": "Spring launch" } }
    ]
  }
}
FieldTypeRequirementDescription
labelstringRequiredNamespaced label with at least one dot, for example com.example.asset-info.v1. Each component uses letters, digits, hyphens, or underscores. The c2pa namespace is reserved. An optional instance suffix such as __2 is allowed.
dataany JSON valueRequiredAssertion content, stored as supplied.
  • Each entry must contain only label and data.

  • Limits: 1 MiB (1,048,576 bytes) as serialized, 64 assertions, and 32 levels of nested arrays and objects. The whole request is separately capped at 8 MiB.

  • Labels must be unique after C2PA version and instance normalization. Use distinct base names for separate assertions. A repeated normalized label returns 4000.

  • MSL marks custom assertions as gathered assertions because the data comes from the caller. Use a label namespace your organization controls; MSL validates the label syntax but does not check domain ownership.

  • Validation failures return 4000. Invalid UTF-8 returns 4002.

4.9 Trace ID

trace_id is optional on every function. MSL stores it as the per-operation correlation ID, tags every log line with it, and forwards it to the signing service as the X-REQUEST-UUID header. It is installed before the request is parsed, so even a malformed request is logged under it. A supplied value is never silently replaced.

Supplied valueBehaviour
NULLMSL generates a UUID v4.
Canonical UUID v4 (36-character hyphenated form)Used unchanged. Surrounding whitespace is ignored.
Any other value, including other UUID versions, the nil or max UUID, and braced, URN, or unhyphenated formsThe call fails with 4000; nothing is signed.
Not valid UTF-8The call fails with 4002.

For two-step CAWG signing, pass NULL to c2pa_cawg_complete to reuse the trace ID from the prepare call, or pass a UUID v4 to override it. If you forward a client-supplied request ID, validate it yourself and pass NULL when it is not a UUID v4.

4.10 Result document

On success, result_json holds a versioned result document and the binary artifacts are named outputs. For c2pa_sign and c2pa_cawg_complete:

{
  "schema_version": 1,
  "manifest_id": "urn:c2pa:3f1e9a52-7b0d-4c1e-9e57-2b6f0d1c8a44",
  "actual_placement": "BOTH",
  "asset_modified_from_input": true,
  "destination_path": "/data/out/photo.jpg",
  "ingredients": [ { "path": "/data/in/reference.jpg", "status": "unsigned", "included": true } ]
}
Field / outputMeaning
manifest_idSigning reference returned by MSL. To select the active C2PA claim, use the active_manifest label returned by your reader.
actual_placementEMBEDDED, SIDECAR, or BOTH. Read this rather than inferring placement from the outputs.
asset_modified_from_inputWhether the signed asset differs from the input.
destination_pathWhere a path source was written. Absent for an input source.
ingredientsPer-ingredient outcomes. Present only when ingredients were requested.
Output assetSigned asset bytes for an input source (always present, may be empty).
Output sidecarDetached Manifest Store for SIDECAR and BOTH.

The manifest report that earlier releases returned as manifest_json is no longer part of the result. The signed asset carries the embedded manifest, the sidecar output carries the detached store, and a reader supplies active_manifest for selecting the active claim; read it with c2patool (see 14).

Use result.manifest_id as a signing reference. To select a claim from a reader’s manifests map, use that reader’s active_manifest label. Do not build a JUMBF URI from result.manifest_id.

Language example setup

Run each example from a project directory containing input/sample.jpeg, output/, and the platform library in rust_binary/. C and Go also use include/c2pa_msl.h. Create output/ before running the examples. Path-based signing requires a destination that does not already exist; choose a new destination when repeating a request.

Export the configuration in section 2 in the shell that starts each language process. The Python and Node.js examples refer to MSL_API_KEY and MSL_SIGNING_URL aliases, so keep those aliases aligned with C2PA_API_KEY and C2PA_SIGNING_SERVICE_URL. Restart the process after changing environment settings. Keep TLS validation and public trust checks enabled.

Example A in each language demonstrates the mandatory request fields. Example B adds provenance, AI disclosure, usage permissions, EXIF extraction and a custom assertion. Rust and C# also provide in-memory examples. Section 12 covers CAWG identity signing separately.

Rust examples

Examples that explicitly use libc2pa_rust.dylib and the C build command below target macOS. On Linux use libc2pa_rust.so; on Windows use c2pa_rust.dll. The C examples use POSIX path functions and require adaptation for Windows. The Go examples include macOS linker directives. Set the credentials before running and create the input/output folders described in the setup instructions.

Rust applications load the platform library at runtime with libloading and call the C functions directly. Export the environment variables from Prerequisites and configuration before running the examples (the library reads them when it first runs, so set C2PA_SKIP_SSL_VALIDATION=false in the shell).

Note: The c2pa-rust-digicert-example 1.1.1 crate and any bindings written for the earlier ABI are not compatible with this release. Use the bindings below instead.

cargo init msl-rust
cd msl-rust
cargo add libloading@0.8 anyhow serde_json

5.1 Shared FFI bindings

Save the following as src/msl.rs. Each example below is a src/main.rs that uses it. Msl::load checks the ABI version, and Msl::call serializes the request, passes any named inputs, copies the result out, and releases it exactly once.

// src/msl.rs: minimal bindings for the MSL C interface (ABI version 2).
#![allow(dead_code)]
use anyhow::{anyhow, bail, Context, Result};
use libloading::Library;
use serde_json::Value;
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::ptr;

const ABI_VERSION: u32 = 2;

#[repr(C)]
struct C2paInput {
    name: *const c_char,
    data: *const u8,
    len: usize,
}

#[repr(C)]
struct C2paOutput {
    name: *mut c_char,
    data: *mut u8,
    len: usize,
}

#[repr(C)]
struct C2paResult {
    error_code: i32,
    error_message: *mut c_char,
    result_json: *mut c_char,
    outputs: *mut C2paOutput,
    output_count: usize,
}

type OperationFn =
    unsafe extern "C" fn(*const c_char, *const C2paInput, usize, *const c_char) -> *mut C2paResult;
type FreeFn = unsafe extern "C" fn(*mut C2paResult);
type AbiFn = unsafe extern "C" fn() -> u32;

/// Result document plus the named binary outputs (for example "asset" and "sidecar").
pub struct Outcome {
    pub result: Value,
    pub outputs: Vec<(String, Vec<u8>)>,
}

impl Outcome {
    pub fn output(&self, name: &str) -> Option<&[u8]> {
        self.outputs.iter().find(|(n, _)| n == name).map(|(_, d)| d.as_slice())
    }
}

pub struct Msl {
    lib: Library,
}

unsafe fn text(pointer: *const c_char) -> Option<String> {
    (!pointer.is_null()).then(|| CStr::from_ptr(pointer).to_string_lossy().into_owned())
}

impl Msl {
    pub fn load(path: &str) -> Result<Self> {
        let lib = unsafe { Library::new(path) }.with_context(|| format!("cannot load {path}"))?;
        let found = unsafe { (*lib.get::<AbiFn>(b"c2pa_abi_version\0")?)() };
        if found != ABI_VERSION {
            bail!("MSL ABI {found} found, {ABI_VERSION} required");
        }
        Ok(Self { lib })
    }

    /// `function` is c2pa_sign, c2pa_cawg_prepare, c2pa_cawg_complete or c2pa_validate_sidecar.
    pub fn call(
        &self,
        function: &str,
        request: &Value,
        inputs: &[(&str, &[u8])],
        trace_id: Option<&str>,
    ) -> Result<Outcome> {
        let request = CString::new(request.to_string())?;
        let names = inputs.iter().map(|(n, _)| CString::new(*n)).collect::<Result<Vec<_>, _>>()?;
        let raw: Vec<C2paInput> = inputs
            .iter()
            .zip(&names)
            .map(|((_, data), name)| C2paInput { name: name.as_ptr(), data: data.as_ptr(), len: data.len() })
            .collect();
        let trace = trace_id.map(CString::new).transpose()?;
        unsafe {
            let operation = self.lib.get::<OperationFn>(format!("{function}\0").as_bytes())?;
            let free = self.lib.get::<FreeFn>(b"c2pa_free_result\0")?;
            let result = operation(
                request.as_ptr(),
                if raw.is_empty() { ptr::null() } else { raw.as_ptr() },
                raw.len(),
                trace.as_ref().map_or(ptr::null(), |t| t.as_ptr()),
            );
            if result.is_null() {
                bail!("MSL returned NULL");
            }
            let r = &*result;
            let outcome = if r.error_code != 0 {
                Err(anyhow!("{}: {}", r.error_code,
                    text(r.error_message).unwrap_or_else(|| "Unknown error".into())))
            } else {
                let outputs = (0..r.output_count)
                    .map(|i| {
                        let o = &*r.outputs.add(i);
                        let data = if o.len == 0 { Vec::new() }
                                   else { std::slice::from_raw_parts(o.data, o.len).to_vec() };
                        (text(o.name).unwrap_or_default(), data)
                    })
                    .collect();
                serde_json::from_str(&text(r.result_json).unwrap_or_default())
                    .map(|result| Outcome { result, outputs })
                    .map_err(Into::into)
            };
            free(result); // exactly once, after everything has been copied out
            outcome
        }
    }
}

5.2 Example A mandatory fields

This example supplies the required fields for path-based standard signing and an explicit tsa_url.

mod msl;

use anyhow::Result;
use msl::Msl;
use serde_json::json;
use std::{env, fs};

fn main() -> Result<()> {
    let msl = Msl::load("rust_binary/libc2pa_rust.dylib")?;
    fs::create_dir_all("output")?;
    let request = json!({
        "schema_version": 1,
        "caller": { "account_id": env::var("MSL_ACCOUNT_ID")? },
        "asset": {
            "filename": "sample.jpeg",
            "source": { "path": fs::canonicalize("input/sample.jpeg")? },
            "destination": { "path": env::current_dir()?.join("output/rust_signed.jpeg") }
        },
        "signing": {
            "manifest_output": "EMBEDDED",
            "roles": ["creator"],
            "tsa_url": "http://timestamp.digicert.com"
        }
    });
    let signed = msl.call("c2pa_sign", &request, &[], None)?;
    println!("Signed file: {}", signed.result["destination_path"]);
    println!("Manifest ID: {}", signed.result["manifest_id"]);
    Ok(())
}

5.3 Example B Extended standard signing with AI disclosure and custom assertions

This example builds an extended standard-signing request with serde_json::json! and passes it to c2pa_sign. The ai_disclosure and initial_action blocks are optional. If ai_disclosure is present, model_type is required. Ingredients use absolute paths to files on the application host; see section 4.6.

mod msl;

use anyhow::Result;
use msl::Msl;
use serde_json::json;
use std::{env, fs};

fn main() -> Result<()> {
    let msl = Msl::load("rust_binary/libc2pa_rust.dylib")?;
    fs::create_dir_all("output")?;

    let request = json!({
        "schema_version": 1,
        "caller": { "account_id": env::var("MSL_ACCOUNT_ID")? },
        "asset": {
            "filename": "sample.jpeg",
            "source": { "path": fs::canonicalize("input/sample.jpeg")? },
            "destination": { "path": env::current_dir()?.join("output/rust_all_fields.jpeg") }
        },
        "signing": {
            "manifest_output": "EMBEDDED",
            "roles": ["creator", "publisher"],
            "tsa_url": "http://timestamp.digicert.com",
            "identity": { "type": "NONE" }
        },
        "provenance": {
            "new_creation": true,
            "created_with_ai": true,
            "digital_source_type":
                "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
            "ai_generator": { "name": "Example Image Generator", "version": "3.1" },
            "initial_action": {
                "description": "Generated the image from a text prompt",
                "when": "2026-08-21T05:59:00Z",
                "software_agent": { "name": "Example Editor", "version": "1.0",
                                    "operating_system": "macOS" }
            },
            "actions": [
                { "action": "c2pa.edited",
                  "description": "Adjusted exposure and contrast",
                  "when": "2026-08-21T06:00:00Z",
                  "software_agent": { "name": "Example Editor", "version": "1.0" } },
                { "action": "c2pa.translated", "description": "Caption translated",
                  "parameters": { "source_language": "en-US", "target_language": "fr-FR" } }
            ]
        },
        "assertions": {
            "ai_disclosure": {
                "model_type": "c2pa.types.model",
                "model_name": "Example AI Model",
                "model_identifier": "https://example.com/models/example",
                "content_profile": { "human_oversight_level": "human_validated" },
                "scientific_domains": ["cs.CV", "cs.LG"],
                "metadata": { "provider": "Example Provider" }
            },
            "usage_rights": {
                "ai_inference": { "permission": "constrained",
                                  "constraints_info": "Internal evaluation only." },
                "generative_ai_training": { "permission": "prohibited" },
                "non_generative_ai_training": { "permission": "allowed" },
                "data_mining_and_analytics": { "permission": "allowed" }
            },
            "exif": { "extract_from_asset": true },
            "custom": [{ "label": "com.example.asset-info.v1",
                         "data": { "assetId": "42844", "campaign": "Spring launch" } }]
        }
    });

    let signed = msl.call("c2pa_sign", &request, &[], None)?; // None: MSL generates the trace ID
    println!("Signed file: {}", signed.result["destination_path"]);
    println!("Manifest ID: {}", signed.result["manifest_id"]);
    Ok(())
}

5.4 Example C In memory standard signing

With an input source, c2pa_sign signs the bytes in memory and returns them as the asset output; the example writes them to the output file. asset.destination must be absent.

mod msl;

use anyhow::{Context, Result};
use msl::Msl;
use serde_json::json;
use std::{env, fs};

fn main() -> Result<()> {
    let msl = Msl::load("rust_binary/libc2pa_rust.dylib")?;
    let input = fs::read("input/sample.jpeg")?;
    fs::create_dir_all("output")?;
    // The asset is an input buffer, so asset.destination must be absent.
    let request = json!({
        "schema_version": 1,
        "caller": { "account_id": env::var("MSL_ACCOUNT_ID")? },
        "asset": { "filename": "sample.jpeg", "source": { "input": "asset" } },
        "signing": {
            "manifest_output": "EMBEDDED",
            "roles": ["creator"],
            "tsa_url": "http://timestamp.digicert.com"
        }
    });
    let signed = msl.call("c2pa_sign", &request, &[("asset", &input)], None)?;
    let bytes = signed.output("asset").context("MSL returned no asset output")?;
    fs::write("output/rust_in_memory_signed.jpeg", bytes)?;
    println!("Output size: {} bytes", bytes.len());
    println!("Manifest ID: {}", signed.result["manifest_id"]);
    Ok(())
}

C examples

Build from the project root so that include/c2pa_msl.h resolves. The request is a JSON string; the examples fill the account ID and the two absolute paths with snprintf. (See the macOS linking note in 1.1.)

clang example_a.c -o example_a -I. -Lrust_binary -lc2pa_rust -Wl,-rpath,@executable_path/rust_binary

6.1 Example A mandatory fields

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "include/c2pa_msl.h"

/* Escape a value for insertion inside a JSON string. */
static int json_escape(const char *input, char *output, size_t capacity) {
  static const char hex[] = "0123456789abcdef";
  size_t used = 0;
  for (const unsigned char *p = (const unsigned char *)input; *p; ++p) {
    size_t needed = (*p < 0x20) ? 6 : ((*p == '"' || *p == '\\') ? 2 : 1);
    if (needed >= capacity || used >= capacity - needed) return 0;
    if (*p < 0x20) {
      output[used++] = '\\'; output[used++] = 'u';
      output[used++] = '0'; output[used++] = '0';
      output[used++] = hex[*p >> 4]; output[used++] = hex[*p & 15];
    } else {
      if (*p == '"' || *p == '\\') output[used++] = '\\';
      output[used++] = (char)*p;
    }
  }
  if (used >= capacity) return 0;
  output[used] = '\0';
  return 1;
}

int main(void) {
  const char *account = getenv("MSL_ACCOUNT_ID");
  if (account == NULL || account[0] == '\0') {
    fprintf(stderr, "Set MSL_ACCOUNT_ID before running this program\n");
    return 1;
  }
  if (c2pa_abi_version() != C2PA_ABI_VERSION) {
    fprintf(stderr, "MSL ABI %u found, %d required\n",
            c2pa_abi_version(), C2PA_ABI_VERSION);
    return 1;
  }

  char source[PATH_MAX];
  if (realpath("input/sample.jpeg", source) == NULL) return 1;
  char destination[PATH_MAX + 32];
  if (getcwd(destination, PATH_MAX) == NULL) return 1;
  snprintf(destination + strlen(destination), 32, "/output/c_signed.jpeg");

  char account_json[4096];
  char source_json[6 * PATH_MAX + 1], destination_json[6 * (PATH_MAX + 32) + 1];
  if (!json_escape(account, account_json, sizeof account_json) ||
      !json_escape(source, source_json, sizeof source_json) ||
      !json_escape(destination, destination_json, sizeof destination_json)) {
    fprintf(stderr, "A request value is too long\n");
    return 1;
  }
  char request[12 * PATH_MAX + 16384];
  int written = snprintf(request, sizeof request,
    "{\"schema_version\":1,"
    "\"caller\":{\"account_id\":\"%s\"},"
    "\"asset\":{\"filename\":\"sample.jpeg\","
      "\"source\":{\"path\":\"%s\"},"
      "\"destination\":{\"path\":\"%s\"}},"
    "\"signing\":{\"manifest_output\":\"EMBEDDED\","
      "\"roles\":[\"creator\"],"
      "\"tsa_url\":\"http://timestamp.digicert.com\"}}",
    account_json, source_json, destination_json);
  if (written < 0 || (size_t)written >= sizeof request) {
    fprintf(stderr, "Request JSON is too large\n");
    return 1;
  }

  C2paResult *r = c2pa_sign(request, NULL, 0, NULL);
  if (r == NULL) return 1;

  int status = 0;
  if (r->error_code != 0) {
    fprintf(stderr, "%d: %s\n", r->error_code,
            r->error_message ? r->error_message : "Unknown error");
    status = 1;
  } else {
    printf("Result: %s\n", r->result_json);
  }
  c2pa_free_result(r);
  return status;
}

6.2 Example B Extended standard signing with AI disclosure and custom assertions

Remove the ai_disclosure or initial_action block if you do not need it. When ai_disclosure is included, model_type is the only required child field. provenance.ingredients is omitted because it needs absolute paths to files on your host; see 4.6. The request template uses %s placeholders. Escape any additional literal percent sign as %% when editing the template.

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "include/c2pa_msl.h"

/* ai_disclosure and initial_action are optional; remove them if not needed.  */
/* provenance.ingredients is omitted because it needs absolute paths (4.6).   */
static const char *REQUEST_TEMPLATE =
  "{\"schema_version\":1,"
  "\"caller\":{\"account_id\":\"%s\"},"
  "\"asset\":{\"filename\":\"sample.jpeg\","
    "\"source\":{\"path\":\"%s\"},"
    "\"destination\":{\"path\":\"%s\"}},"
  "\"signing\":{\"manifest_output\":\"EMBEDDED\","
    "\"roles\":[\"creator\",\"publisher\"],"
    "\"tsa_url\":\"http://timestamp.digicert.com\","
    "\"identity\":{\"type\":\"NONE\"}},"
  "\"provenance\":{"
    "\"new_creation\":true,"
    "\"created_with_ai\":true,"
    "\"digital_source_type\":\"http://cv.iptc.org/newscodes/digitalsourcetype/"
      "trainedAlgorithmicMedia\","
    "\"ai_generator\":{\"name\":\"Example Image Generator\",\"version\":\"3.1\"},"
    "\"initial_action\":{"
      "\"description\":\"Generated the image from a text prompt\","
      "\"when\":\"2026-08-21T05:59:00Z\","
      "\"software_agent\":{\"name\":\"Example Editor\",\"version\":\"1.0\","
        "\"operating_system\":\"macOS\"}},"
    "\"actions\":["
      "{\"action\":\"c2pa.edited\","
        "\"description\":\"Adjusted exposure and contrast\","
        "\"when\":\"2026-08-21T06:00:00Z\","
        "\"software_agent\":{\"name\":\"Example Editor\",\"version\":\"1.0\"}},"
      "{\"action\":\"c2pa.translated\",\"description\":\"Caption translated\","
        "\"parameters\":{\"source_language\":\"en-US\",\"target_language\":\"fr-FR\"}}]},"
  "\"assertions\":{"
    "\"ai_disclosure\":{"
      "\"model_type\":\"c2pa.types.model\","
      "\"model_name\":\"Example AI Model\","
      "\"model_identifier\":\"https://example.com/models/example\","
      "\"content_profile\":{\"human_oversight_level\":\"human_validated\"},"
      "\"scientific_domains\":[\"cs.CV\",\"cs.LG\"],"
      "\"metadata\":{\"provider\":\"Example Provider\"}},"
    "\"usage_rights\":{"
      "\"ai_inference\":{\"permission\":\"constrained\","
        "\"constraints_info\":\"Internal evaluation only.\"},"
      "\"generative_ai_training\":{\"permission\":\"prohibited\"},"
      "\"non_generative_ai_training\":{\"permission\":\"allowed\"},"
      "\"data_mining_and_analytics\":{\"permission\":\"allowed\"}},"
    "\"exif\":{\"extract_from_asset\":true},"
    "\"custom\":[{\"label\":\"com.example.asset-info.v1\","
      "\"data\":{\"assetId\":\"42844\",\"campaign\":\"Spring launch\"}}]}}";

/* Escape a value for insertion inside a JSON string. */
static int json_escape(const char *input, char *output, size_t capacity) {
  static const char hex[] = "0123456789abcdef";
  size_t used = 0;
  for (const unsigned char *p = (const unsigned char *)input; *p; ++p) {
    size_t needed = (*p < 0x20) ? 6 : ((*p == '"' || *p == '\\') ? 2 : 1);
    if (needed >= capacity || used >= capacity - needed) return 0;
    if (*p < 0x20) {
      output[used++] = '\\'; output[used++] = 'u';
      output[used++] = '0'; output[used++] = '0';
      output[used++] = hex[*p >> 4]; output[used++] = hex[*p & 15];
    } else {
      if (*p == '"' || *p == '\\') output[used++] = '\\';
      output[used++] = (char)*p;
    }
  }
  if (used >= capacity) return 0;
  output[used] = '\0';
  return 1;
}

int main(void) {
  const char *account = getenv("MSL_ACCOUNT_ID");
  if (account == NULL || account[0] == '\0') {
    fprintf(stderr, "Set MSL_ACCOUNT_ID before running this program\n");
    return 1;
  }
  if (c2pa_abi_version() != C2PA_ABI_VERSION) return 1;

  char source[PATH_MAX], destination[PATH_MAX + 32];
  if (realpath("input/sample.jpeg", source) == NULL) return 1;
  if (getcwd(destination, PATH_MAX) == NULL) return 1;
  strcat(destination, "/output/c_all_fields.jpeg");

  char account_json[4096];
  char source_json[6 * PATH_MAX + 1], destination_json[6 * (PATH_MAX + 32) + 1];
  if (!json_escape(account, account_json, sizeof account_json) ||
      !json_escape(source, source_json, sizeof source_json) ||
      !json_escape(destination, destination_json, sizeof destination_json)) {
    fprintf(stderr, "A request value is too long\n");
    return 1;
  }
  char request[12 * PATH_MAX + 16384];
  int written = snprintf(request, sizeof request, REQUEST_TEMPLATE,
           account_json, source_json, destination_json);
  if (written < 0 || (size_t)written >= sizeof request) {
    fprintf(stderr, "Request JSON is too large\n");
    return 1;
  }

  /* A NULL trace_id makes MSL generate a UUID v4. */
  C2paResult *r = c2pa_sign(request, NULL, 0, NULL);
  if (r == NULL) return 1;

  int status = 0;
  if (r->error_code != 0) {
    fprintf(stderr, "%d: %s\n", r->error_code,
            r->error_message ? r->error_message : "Unknown error");
    status = 1;
  } else {
    printf("Result: %s\n", r->result_json);
  }
  c2pa_free_result(r);
  return status;
}

C# examples

The C# examples use DllImport P/Invoke and System.Text.Json, and target .NET 8 or later. Create a console project, copy Msl.cs and the example as Program.cs, and keep rust_binary/ and input/ in the working directory.

dotnet new console -n MslCSharp --framework net10.0
cd MslCSharp
# Add Msl.cs and replace Program.cs with one of the examples below.
# Export C2PA_SIGNING_SERVICE_URL, C2PA_API_KEY and C2PA_SKIP_SSL_VALIDATION first.
dotnet run

Environment: On macOS and Linux, Environment.SetEnvironmentVariable does not change the native process environment that MSL reads. Export C2PA_SIGNING_SERVICE_URL, C2PA_API_KEY, and C2PA_SKIP_SSL_VALIDATION=false in the shell that starts dotnet.

7.1 Shared P/Invoke bindings

Save the following as Msl.cs. Msl.Load resolves the c2pa_rust import to the library in rust_binary/ for the current platform and checks the ABI version. Msl.Sign serializes the request, copies the result and its outputs into managed memory, and releases the native result exactly once. It can also pass named inputs; Msl.ValidateSidecar shows the same call with inputs.

// Msl.cs: minimal P/Invoke bindings for the MSL C interface (ABI version 2).
using System.Runtime.InteropServices;
using System.Text.Json;

public sealed class MslException : Exception
{
    public int Code { get; }
    public MslException(int code, string message) : base($"{code}: {message}") => Code = code;
}

public sealed record MslOutcome(JsonElement Result, Dictionary<string, byte[]> Outputs);

public static class Msl
{
    private const int AbiVersion = 2;
    private const string Library = "c2pa_rust";

    [StructLayout(LayoutKind.Sequential)]
    private struct C2paInput
    {
        public IntPtr Name;   // const char *
        public IntPtr Data;   // const uint8_t *
        public UIntPtr Len;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct C2paOutput
    {
        public IntPtr Name;   // char *
        public IntPtr Data;   // uint8_t *
        public UIntPtr Len;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct C2paResult
    {
        public int ErrorCode;
        public IntPtr ErrorMessage;
        public IntPtr ResultJson;
        public IntPtr Outputs;
        public UIntPtr OutputCount;
    }

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] private static extern uint c2pa_abi_version();

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    private static extern IntPtr c2pa_sign(
        [MarshalAs(UnmanagedType.LPUTF8Str)] string requestJson,
        IntPtr inputs, UIntPtr inputCount,
        [MarshalAs(UnmanagedType.LPUTF8Str)] string? traceId);

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
    private static extern IntPtr c2pa_validate_sidecar(
        [MarshalAs(UnmanagedType.LPUTF8Str)] string requestJson,
        IntPtr inputs, UIntPtr inputCount,
        [MarshalAs(UnmanagedType.LPUTF8Str)] string? traceId);

    [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] private static extern void c2pa_free_result(IntPtr result);

    /// <summary>Resolve "c2pa_rust" to the library in rust_binary/ and check the ABI version.</summary>
    public static void Load(string directory = "rust_binary")
    {
        string file = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c2pa_rust.dll"
                    : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "libc2pa_rust.dylib"
                    : "libc2pa_rust.so";
        NativeLibrary.SetDllImportResolver(typeof(Msl).Assembly, (name, _, _) =>
            name == Library ? NativeLibrary.Load(Path.GetFullPath(Path.Combine(directory, file)))
                            : IntPtr.Zero);
        uint found = c2pa_abi_version();
        if (found != AbiVersion)
            throw new InvalidOperationException($"MSL ABI {found} found, {AbiVersion} required");
    }

    public static MslOutcome Sign(
        object request, Dictionary<string, byte[]>? inputs = null, string? traceId = null) =>
        Call(c2pa_sign, request, inputs ?? new Dictionary<string, byte[]>(), traceId);

    public static MslOutcome ValidateSidecar(
        object request, Dictionary<string, byte[]> inputs, string? traceId = null) =>
        Call(c2pa_validate_sidecar, request, inputs, traceId);

    private delegate IntPtr Operation(string json, IntPtr inputs, UIntPtr count, string? trace);

    private static MslOutcome Call(
        Operation operation, object request, Dictionary<string, byte[]> inputs, string? traceId)
    {
        string json = JsonSerializer.Serialize(request);
        var pinned = new List<GCHandle>();
        var names = new List<IntPtr>();
        IntPtr table = IntPtr.Zero;
        try
        {
            if (inputs.Count > 0)
            {
                int size = Marshal.SizeOf<C2paInput>();
                table = Marshal.AllocHGlobal(size * inputs.Count);
                int i = 0;
                foreach (var (name, data) in inputs)
                {
                    var handle = GCHandle.Alloc(data, GCHandleType.Pinned);
                    pinned.Add(handle);
                    IntPtr namePointer = Marshal.StringToCoTaskMemUTF8(name);
                    names.Add(namePointer);
                    Marshal.StructureToPtr(new C2paInput
                    {
                        Name = namePointer,
                        Data = handle.AddrOfPinnedObject(),
                        Len = (UIntPtr)data.Length,
                    }, table + i++ * size, false);
                }
            }

            IntPtr pointer = operation(json, table, (UIntPtr)inputs.Count, traceId);
            if (pointer == IntPtr.Zero) throw new InvalidOperationException("MSL returned NULL");
            try
            {
                var r = Marshal.PtrToStructure<C2paResult>(pointer);
                if (r.ErrorCode != 0)
                    throw new MslException(r.ErrorCode,
                        Marshal.PtrToStringUTF8(r.ErrorMessage) ?? "Unknown error");

                var outputs = new Dictionary<string, byte[]>();
                int count = checked((int)r.OutputCount.ToUInt64());
                int outputSize = Marshal.SizeOf<C2paOutput>();
                for (int i = 0; i < count; i++)
                {
                    var o = Marshal.PtrToStructure<C2paOutput>(r.Outputs + i * outputSize);
                    var bytes = new byte[checked((int)o.Len.ToUInt64())];
                    if (bytes.Length > 0) Marshal.Copy(o.Data, bytes, 0, bytes.Length);
                    outputs[Marshal.PtrToStringUTF8(o.Name) ?? ""] = bytes;
                }
                using var document = JsonDocument.Parse(Marshal.PtrToStringUTF8(r.ResultJson)!);
                return new MslOutcome(document.RootElement.Clone(), outputs);
            }
            finally
            {
                c2pa_free_result(pointer); // exactly once, after everything has been copied out
            }
        }
        finally
        {
            foreach (var handle in pinned) handle.Free();
            foreach (var name in names) Marshal.FreeCoTaskMem(name);
            if (table != IntPtr.Zero) Marshal.FreeHGlobal(table);
        }
    }
}

7.2 Example A mandatory fields

// Top-level program (Program.cs). Build: dotnet new console, then add Msl.cs.
// Export C2PA_SIGNING_SERVICE_URL, C2PA_API_KEY and C2PA_SKIP_SSL_VALIDATION=false
// in the shell first. On macOS and Linux, Environment.SetEnvironmentVariable
// does not change the native process environment that MSL reads.

Msl.Load("rust_binary");
Directory.CreateDirectory("output");

var request = new
{
    schema_version = 1,
    caller = new { account_id = Environment.GetEnvironmentVariable("MSL_ACCOUNT_ID") },
    asset = new
    {
        filename = "sample.jpeg",
        source = new { path = Path.GetFullPath("input/sample.jpeg") },
        destination = new { path = Path.GetFullPath("output/csharp_signed.jpeg") },
    },
    signing = new
    {
        manifest_output = "EMBEDDED",
        roles = new[] { "creator" },
        tsa_url = "http://timestamp.digicert.com",
    },
};

try
{
    var signed = Msl.Sign(request);
    Console.WriteLine($"Signed file: {signed.Result.GetProperty("destination_path")}");
    Console.WriteLine($"Manifest ID: {signed.Result.GetProperty("manifest_id")}");
}
catch (MslException e)
{
    Console.Error.WriteLine($"MSL error {e.Code}: {e.Message}");
    return 1;
}
return 0;

7.3 Example B Extended standard signing with AI disclosure and custom assertions

The request is an anonymous object whose property names are the request field names. Remove the ai_disclosure or initial_action block if you do not need it. When ai_disclosure is included, model_type is the only required child field. provenance.ingredients is omitted because it needs absolute paths to files on your host; see 4.6.

// Top-level program (Program.cs); uses the Msl class from Msl.cs.
Msl.Load("rust_binary");
Directory.CreateDirectory("output");

// ai_disclosure and initial_action are optional; remove them if not needed.
// provenance.ingredients is omitted because it needs absolute paths (4.6).
var request = new
{
    schema_version = 1,
    caller = new { account_id = Environment.GetEnvironmentVariable("MSL_ACCOUNT_ID") },
    asset = new
    {
        filename = "sample.jpeg",
        source = new { path = Path.GetFullPath("input/sample.jpeg") },
        destination = new { path = Path.GetFullPath("output/csharp_all_fields.jpeg") },
    },
    signing = new
    {
        manifest_output = "EMBEDDED",
        roles = new[] { "creator", "publisher" },
        tsa_url = "http://timestamp.digicert.com",
        identity = new { type = "NONE" },
    },
    provenance = new
    {
        new_creation = true,
        created_with_ai = true,
        digital_source_type =
            "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
        ai_generator = new { name = "Example Image Generator", version = "3.1" },
        initial_action = new
        {
            description = "Generated the image from a text prompt",
            when = "2026-08-21T05:59:00Z",
            software_agent = new { name = "Example Editor", version = "1.0", operating_system = "macOS" },
        },
        actions = new object[]
        {
            new
            {
                action = "c2pa.edited",
                description = "Adjusted exposure and contrast",
                when = "2026-08-21T06:00:00Z",
                software_agent = new { name = "Example Editor", version = "1.0" },
            },
            new
            {
                action = "c2pa.translated",
                description = "Caption translated",
                parameters = new { source_language = "en-US", target_language = "fr-FR" },
            },
        },
    },
    assertions = new
    {
        ai_disclosure = new
        {
            model_type = "c2pa.types.model",
            model_name = "Example AI Model",
            model_identifier = "https://example.com/models/example",
            content_profile = new { human_oversight_level = "human_validated" },
            scientific_domains = new[] { "cs.CV", "cs.LG" },
            metadata = new { provider = "Example Provider" },
        },
        usage_rights = new
        {
            ai_inference = new { permission = "constrained", constraints_info = "Internal evaluation only." },
            generative_ai_training = new { permission = "prohibited" },
            non_generative_ai_training = new { permission = "allowed" },
            data_mining_and_analytics = new { permission = "allowed" },
        },
        exif = new { extract_from_asset = true },
        custom = new[]
        {
            new { label = "com.example.asset-info.v1", data = new { assetId = "42844", campaign = "Spring launch" } },
        },
    },
};

try
{
    var signed = Msl.Sign(request); // no trace ID: MSL generates a UUID v4
    Console.WriteLine(signed.Result.GetRawText());
}
catch (MslException e)
{
    Console.Error.WriteLine($"MSL error {e.Code}: {e.Message}");
    return 1;
}
return 0;

7.4 Example C In memory standard signing

To sign bytes instead of a file, use an input source and pass the bytes as a named input. The signed asset comes back as the asset output.

Msl.Load("rust_binary");
Directory.CreateDirectory("output");

var request = new
{
    schema_version = 1,
    caller = new { account_id = Environment.GetEnvironmentVariable("MSL_ACCOUNT_ID") },
    asset = new { filename = "sample.jpeg", source = new { input = "asset" } },
    signing = new
    {
        manifest_output = "EMBEDDED",
        roles = new[] { "creator" },
        tsa_url = "http://timestamp.digicert.com",
    },
};

var inputs = new Dictionary<string, byte[]> { ["asset"] = File.ReadAllBytes("input/sample.jpeg") };
var signed = Msl.Sign(request, inputs);
File.WriteAllBytes("output/csharp_in_memory_signed.jpeg", signed.Outputs["asset"]);
Console.WriteLine($"Manifest ID: {signed.Result.GetProperty("manifest_id")}");

Python examples

The Python examples use the standard ctypes module and Python 3.9 or later.

8.1 Shared FFI bindings

Save the following as msl.py. Msl checks the ABI version on load. Msl.call returns the result document and a dictionary of named outputs, raises MslError on failure, and always releases the native result.

"""msl.py: minimal ctypes bindings for the MSL C interface (ABI version 2)."""
import ctypes
import json
from pathlib import Path

ABI_VERSION = 2


class C2paInput(ctypes.Structure):
    _fields_ = [("name", ctypes.c_char_p),
                ("data", ctypes.c_char_p),
                ("len", ctypes.c_size_t)]


class C2paOutput(ctypes.Structure):
    _fields_ = [("name", ctypes.c_void_p),
                ("data", ctypes.c_void_p),
                ("len", ctypes.c_size_t)]


class C2paResult(ctypes.Structure):
    _fields_ = [("error_code", ctypes.c_int32),
                ("error_message", ctypes.c_void_p),
                ("result_json", ctypes.c_void_p),
                ("outputs", ctypes.POINTER(C2paOutput)),
                ("output_count", ctypes.c_size_t)]


class MslError(RuntimeError):
    def __init__(self, code, message):
        super().__init__(f"{code}: {message}")
        self.code = code


def _text(pointer):
    return ctypes.string_at(pointer).decode("utf-8") if pointer else None


class Msl:
    def __init__(self, library_path):
        self._lib = ctypes.CDLL(str(Path(library_path).resolve()))
        self._lib.c2pa_abi_version.argtypes = []
        self._lib.c2pa_abi_version.restype = ctypes.c_uint32
        found = self._lib.c2pa_abi_version()
        if found != ABI_VERSION:
            raise RuntimeError(f"MSL ABI {found} found, {ABI_VERSION} required")
        for name in ("c2pa_sign", "c2pa_cawg_prepare",
                     "c2pa_cawg_complete", "c2pa_validate_sidecar"):
            function = getattr(self._lib, name)
            function.argtypes = [ctypes.c_char_p, ctypes.POINTER(C2paInput),
                                 ctypes.c_size_t, ctypes.c_char_p]
            function.restype = ctypes.POINTER(C2paResult)
        self._lib.c2pa_free_result.argtypes = [ctypes.POINTER(C2paResult)]
        self._lib.c2pa_free_result.restype = None

    def call(self, function, request, inputs=None, trace_id=None):
        """Return (result_document, {output_name: bytes}); raise MslError on failure."""
        inputs = inputs or {}
        raw = (C2paInput * len(inputs))(
            *[C2paInput(name.encode(), data, len(data))
              for name, data in inputs.items()])
        pointer = getattr(self._lib, function)(
            json.dumps(request).encode("utf-8"),
            raw if inputs else None,
            len(inputs),
            trace_id.encode() if trace_id else None)
        if not pointer:
            raise RuntimeError("MSL returned NULL")
        try:
            result = pointer.contents
            if result.error_code:
                raise MslError(result.error_code,
                               _text(result.error_message) or "Unknown error")
            outputs = {}
            for i in range(result.output_count):
                output = result.outputs[i]
                outputs[_text(output.name)] = (
                    ctypes.string_at(output.data, output.len) if output.len else b"")
            return json.loads(_text(result.result_json)), outputs
        finally:
            self._lib.c2pa_free_result(pointer)

8.2 Example A mandatory fields

import os
from pathlib import Path

from msl import Msl

# MSL reads these when the library loads, so set them first.
os.environ["C2PA_SIGNING_SERVICE_URL"] = os.environ["MSL_SIGNING_URL"]
os.environ["C2PA_API_KEY"] = os.environ["MSL_API_KEY"]
os.environ["C2PA_SKIP_SSL_VALIDATION"] = "false"

msl = Msl("rust_binary/libc2pa_rust.dylib")
Path("output").mkdir(exist_ok=True)

request = {
    "schema_version": 1,
    "caller": {"account_id": os.environ["MSL_ACCOUNT_ID"]},
    "asset": {
        "filename": "sample.jpeg",
        "source": {"path": str(Path("input/sample.jpeg").resolve())},
        "destination": {"path": str(Path("output/python_signed.jpeg").resolve())},
    },
    "signing": {
        "manifest_output": "EMBEDDED",
        "roles": ["creator"],
        "tsa_url": "http://timestamp.digicert.com",
    },
}

result, _ = msl.call("c2pa_sign", request)
print("Signed file:", result["destination_path"])
print("Manifest ID:", result["manifest_id"])

8.3 Example B Extended standard signing with AI disclosure and custom assertions

Remove the ai_disclosure or initial_action block if you do not need it. When ai_disclosure is included, model_type is the only required child field. provenance.ingredients is omitted because it needs absolute paths to files on your host; see 4.6.

import os
from pathlib import Path

from msl import Msl

os.environ["C2PA_SIGNING_SERVICE_URL"] = os.environ["MSL_SIGNING_URL"]
os.environ["C2PA_API_KEY"] = os.environ["MSL_API_KEY"]
os.environ["C2PA_SKIP_SSL_VALIDATION"] = "false"
os.environ["SKIP_C2PA_PUBLIC_TRUST_LIST_CHECK"] = "false"
os.environ["C2PA_CLAIM_GENERATOR_NAME"] = "DigiCert Content Trust Manager"

msl = Msl("rust_binary/libc2pa_rust.dylib")
Path("output").mkdir(exist_ok=True)

# ai_disclosure and initial_action are optional; remove them if not needed.
# provenance.ingredients is omitted because it needs absolute paths on your host (4.6).
request = {
    "schema_version": 1,
    "caller": {"account_id": os.environ["MSL_ACCOUNT_ID"]},
    "asset": {
        "filename": "sample.jpeg",
        "source": {"path": str(Path("input/sample.jpeg").resolve())},
        "destination": {"path": str(Path("output/python_all_fields.jpeg").resolve())},
    },
    "signing": {
        "manifest_output": "EMBEDDED",
        "roles": ["creator", "publisher"],
        "tsa_url": "http://timestamp.digicert.com",
        "identity": {"type": "NONE"},
    },
    "provenance": {
        "new_creation": True,
        "created_with_ai": True,
        "digital_source_type":
            "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
        "ai_generator": {"name": "Example Image Generator", "version": "3.1"},
        "initial_action": {
            "description": "Generated the image from a text prompt",
            "when": "2026-08-21T05:59:00Z",
            "software_agent": {"name": "Example Editor", "version": "1.0",
                               "operating_system": "macOS"},
        },
        "actions": [
            {"action": "c2pa.edited",
             "description": "Adjusted exposure and contrast",
             "when": "2026-08-21T06:00:00Z",
             "software_agent": {"name": "Example Editor", "version": "1.0"}},
            {"action": "c2pa.translated",
             "description": "Caption translated",
             "parameters": {"source_language": "en-US", "target_language": "fr-FR"}},
        ],
    },
    "assertions": {
        "ai_disclosure": {
            "model_type": "c2pa.types.model",
            "model_name": "Example AI Model",
            "model_identifier": "https://example.com/models/example",
            "content_profile": {"human_oversight_level": "human_validated"},
            "scientific_domains": ["cs.CV", "cs.LG"],
            "metadata": {"provider": "Example Provider"},
        },
        "usage_rights": {
            "ai_inference": {"permission": "constrained",
                             "constraints_info": "Internal evaluation only."},
            "generative_ai_training": {"permission": "prohibited"},
            "non_generative_ai_training": {"permission": "allowed"},
            "data_mining_and_analytics": {"permission": "allowed"},
        },
        "exif": {"extract_from_asset": True},
        "custom": [{"label": "com.example.asset-info.v1",
                    "data": {"assetId": "42844", "campaign": "Spring launch"}}],
    },
}

result, _ = msl.call("c2pa_sign", request, trace_id=None)  # None: MSL generates a UUID v4
print("Signed file:", result["destination_path"])
print("Manifest ID:", result["manifest_id"])
for item in result.get("ingredients", []):
    print(item["path"], item["status"])

Node js examples

Install Koffi 3.3 or later (the examples were run with Koffi 3.3.6 on Node.js 26):

npm install koffi@3.3.6

9.1 Shared FFI bindings

Save the following as msl.js. load checks the ABI version and returns call(operation, request, inputs, traceId), which returns the result document and a dictionary of output buffers, throws MslError on failure, and always releases the native result.

// msl.js: minimal Koffi bindings for the MSL C interface (ABI version 2).
const koffi = require("koffi");
const path = require("path");

const ABI_VERSION = 2;

const C2paInput = koffi.struct("C2paInput", {
  name: "const char *", data: "const uint8_t *", len: "size_t",
});
const C2paOutput = koffi.struct("C2paOutput", {
  name: "char *", data: "uint8_t *", len: "size_t",
});
const C2paResult = koffi.struct("C2paResult", {
  error_code: "int32_t", error_message: "char *", result_json: "char *",
  outputs: koffi.pointer(C2paOutput), output_count: "size_t",
});

class MslError extends Error {
  constructor(code, message) { super(`${code}: ${message}`); this.code = code; }
}

function load(libraryPath) {
  const lib = koffi.load(path.resolve(libraryPath));
  const found = lib.func("uint32_t c2pa_abi_version()")();
  if (found !== ABI_VERSION) {
    throw new Error(`MSL ABI ${found} found, ${ABI_VERSION} required`);
  }
  const free = lib.func("void c2pa_free_result(C2paResult *result)");
  const operations = {};
  for (const name of ["c2pa_sign", "c2pa_cawg_prepare",
                      "c2pa_cawg_complete", "c2pa_validate_sidecar"]) {
    operations[name] = lib.func(
      `C2paResult *${name}(const char *request_json, const C2paInput *inputs, ` +
      "size_t input_count, const char *trace_id)");
  }

  // inputs: { name: Buffer }. Returns { result, outputs: { name: Buffer } }.
  function call(operation, request, inputs = {}, traceId = null) {
    const list = Object.entries(inputs).map(
      ([name, data]) => ({ name, data, len: data.length }));
    const pointer = operations[operation](
      JSON.stringify(request), list.length ? list : null, list.length, traceId);
    if (!pointer) throw new Error("MSL returned NULL");
    try {
      const r = koffi.decode(pointer, C2paResult);
      if (r.error_code !== 0) {
        throw new MslError(r.error_code, r.error_message || "Unknown error");
      }
      const outputs = {};
      const count = Number(r.output_count);
      if (count > 0) {
        koffi.decode(r.outputs, C2paOutput, count).forEach((o) => {
          const length = Number(o.len);
          outputs[o.name] = length ? Buffer.from(koffi.decode(o.data, "uint8_t", length))
                                   : Buffer.alloc(0);
        });
      }
      return { result: JSON.parse(r.result_json), outputs };
    } finally {
      free(pointer);
    }
  }
  return { call };
}

module.exports = { load, MslError };

9.2 Example A mandatory fields

const fs = require("fs");
const path = require("path");
const { load } = require("./msl");

// MSL reads these when the library loads, so set them first.
process.env.C2PA_SIGNING_SERVICE_URL = process.env.MSL_SIGNING_URL;
process.env.C2PA_API_KEY = process.env.MSL_API_KEY;
process.env.C2PA_SKIP_SSL_VALIDATION = "false";

const msl = load("rust_binary/libc2pa_rust.dylib");
fs.mkdirSync("output", { recursive: true });

const { result } = msl.call("c2pa_sign", {
  schema_version: 1,
  caller: { account_id: process.env.MSL_ACCOUNT_ID },
  asset: {
    filename: "sample.jpeg",
    source: { path: path.resolve("input/sample.jpeg") },
    destination: { path: path.resolve("output/node_signed.jpeg") },
  },
  signing: {
    manifest_output: "EMBEDDED",
    roles: ["creator"],
    tsa_url: "http://timestamp.digicert.com",
  },
});

console.log("Signed file:", result.destination_path);
console.log("Manifest ID:", result.manifest_id);

9.3 Example B Extended standard signing with AI disclosure and custom assertions

Remove the ai_disclosure or initial_action block if you do not need it. When ai_disclosure is included, model_type is the only required child field. provenance.ingredients is omitted because it needs absolute paths to files on your host; see 4.6.

const fs = require("fs");
const path = require("path");
const { load } = require("./msl");

process.env.C2PA_SIGNING_SERVICE_URL = process.env.MSL_SIGNING_URL;
process.env.C2PA_API_KEY = process.env.MSL_API_KEY;
process.env.C2PA_SKIP_SSL_VALIDATION = "false";
process.env.SKIP_C2PA_PUBLIC_TRUST_LIST_CHECK = "false";
process.env.C2PA_CLAIM_GENERATOR_NAME = "DigiCert Content Trust Manager";

const msl = load("rust_binary/libc2pa_rust.dylib");
fs.mkdirSync("output", { recursive: true });

// ai_disclosure and initial_action are optional; remove them if not needed.
// provenance.ingredients is omitted because it needs absolute paths on your host (4.6).
const request = {
  schema_version: 1,
  caller: { account_id: process.env.MSL_ACCOUNT_ID },
  asset: {
    filename: "sample.jpeg",
    source: { path: path.resolve("input/sample.jpeg") },
    destination: { path: path.resolve("output/node_all_fields.jpeg") },
  },
  signing: {
    manifest_output: "EMBEDDED",
    roles: ["creator", "publisher"],
    tsa_url: "http://timestamp.digicert.com",
    identity: { type: "NONE" },
  },
  provenance: {
    new_creation: true,
    created_with_ai: true,
    digital_source_type:
      "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
    ai_generator: { name: "Example Image Generator", version: "3.1" },
    initial_action: {
      description: "Generated the image from a text prompt",
      when: "2026-08-21T05:59:00Z",
      software_agent: { name: "Example Editor", version: "1.0", operating_system: "macOS" },
    },
    actions: [
      { action: "c2pa.edited", description: "Adjusted exposure and contrast",
        when: "2026-08-21T06:00:00Z",
        software_agent: { name: "Example Editor", version: "1.0" } },
      { action: "c2pa.translated", description: "Caption translated",
        parameters: { source_language: "en-US", target_language: "fr-FR" } },
    ],
  },
  assertions: {
    ai_disclosure: {
      model_type: "c2pa.types.model",
      model_name: "Example AI Model",
      model_identifier: "https://example.com/models/example",
      content_profile: { human_oversight_level: "human_validated" },
      scientific_domains: ["cs.CV", "cs.LG"],
      metadata: { provider: "Example Provider" },
    },
    usage_rights: {
      ai_inference: { permission: "constrained", constraints_info: "Internal evaluation only." },
      generative_ai_training: { permission: "prohibited" },
      non_generative_ai_training: { permission: "allowed" },
      data_mining_and_analytics: { permission: "allowed" },
    },
    exif: { extract_from_asset: true },
    custom: [{ label: "com.example.asset-info.v1",
               data: { assetId: "42844", campaign: "Spring launch" } }],
  },
};

const { result } = msl.call("c2pa_sign", request); // trace ID omitted: MSL generates one
console.log("Signed file:", result.destination_path);
console.log("Manifest ID:", result.manifest_id);
for (const item of result.ingredients || []) console.log(item.path, item.status);

Go examples

The Go examples use cgo and the C header. Put main.go next to include/ and rust_binary/. ${SRCDIR} is the directory that holds the source file. (See the macOS linking note in 1.1.)

10.1 Example A mandatory fields

package main

/*
#cgo CFLAGS: -I${SRCDIR}/include
#cgo darwin LDFLAGS: -L${SRCDIR}/rust_binary -lc2pa_rust -Wl,-rpath,${SRCDIR}/rust_binary
#cgo linux LDFLAGS: -L${SRCDIR}/rust_binary -lc2pa_rust -Wl,-rpath,${SRCDIR}/rust_binary
#include <stdlib.h>
#include "c2pa_msl.h"
*/
import "C"

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"unsafe"
)

// sign calls c2pa_sign with a path-based request and returns the result document.
func sign(request map[string]any) (map[string]any, error) {
	if v := uint32(C.c2pa_abi_version()); v != C.C2PA_ABI_VERSION {
		return nil, fmt.Errorf("MSL ABI %d found, %d required", v, C.C2PA_ABI_VERSION)
	}
	body, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}
	cRequest := C.CString(string(body))
	defer C.free(unsafe.Pointer(cRequest))

	r := C.c2pa_sign(cRequest, nil, 0, nil) // nil trace ID: MSL generates a UUID v4
	if r == nil {
		return nil, fmt.Errorf("MSL returned NULL")
	}
	defer C.c2pa_free_result(r)
	if r.error_code != 0 {
		return nil, fmt.Errorf("%d: %s", int32(r.error_code), C.GoString(r.error_message))
	}
	var result map[string]any
	err = json.Unmarshal([]byte(C.GoString(r.result_json)), &result)
	return result, err
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	must(os.Setenv("C2PA_SIGNING_SERVICE_URL", os.Getenv("MSL_SIGNING_URL")))
	must(os.Setenv("C2PA_API_KEY", os.Getenv("MSL_API_KEY")))
	must(os.Setenv("C2PA_SKIP_SSL_VALIDATION", "false"))

	source, err := filepath.Abs("input/sample.jpeg")
	must(err)
	destination, err := filepath.Abs("output/go_signed.jpeg")
	must(err)
	must(os.MkdirAll("output", 0o755))

	result, err := sign(map[string]any{
		"schema_version": 1,
		"caller":         map[string]any{"account_id": os.Getenv("MSL_ACCOUNT_ID")},
		"asset": map[string]any{
			"filename":    "sample.jpeg",
			"source":      map[string]any{"path": source},
			"destination": map[string]any{"path": destination},
		},
		"signing": map[string]any{
			"manifest_output": "EMBEDDED",
			"roles":           []string{"creator"},
			"tsa_url":         "http://timestamp.digicert.com",
		},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("Signed file:", result["destination_path"])
	fmt.Println("Manifest ID:", result["manifest_id"])
}

10.2 Example B Extended standard signing with AI disclosure and custom assertions

Remove the ai_disclosure or initial_action block if you do not need it. When ai_disclosure is included, model_type is the only required child field. provenance.ingredients is omitted because it needs absolute paths to files on your host; see 4.6.

package main

/*
#cgo CFLAGS: -I${SRCDIR}/include
#cgo darwin LDFLAGS: -L${SRCDIR}/rust_binary -lc2pa_rust -Wl,-rpath,${SRCDIR}/rust_binary
#cgo linux LDFLAGS: -L${SRCDIR}/rust_binary -lc2pa_rust -Wl,-rpath,${SRCDIR}/rust_binary
#include <stdlib.h>
#include "c2pa_msl.h"
*/
import "C"

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"unsafe"
)

type obj = map[string]any

func must(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	must(os.Setenv("C2PA_SIGNING_SERVICE_URL", os.Getenv("MSL_SIGNING_URL")))
	must(os.Setenv("C2PA_API_KEY", os.Getenv("MSL_API_KEY")))
	must(os.Setenv("C2PA_SKIP_SSL_VALIDATION", "false"))
	must(os.Setenv("SKIP_C2PA_PUBLIC_TRUST_LIST_CHECK", "false"))
	must(os.Setenv("C2PA_CLAIM_GENERATOR_NAME", "DigiCert Content Trust Manager"))

	if v := uint32(C.c2pa_abi_version()); v != C.C2PA_ABI_VERSION {
		panic(fmt.Sprintf("MSL ABI %d found, %d required", v, C.C2PA_ABI_VERSION))
	}
	source, err := filepath.Abs("input/sample.jpeg")
	must(err)
	destination, err := filepath.Abs("output/go_all_fields.jpeg")
	must(err)
	must(os.MkdirAll("output", 0o755))

	// ai_disclosure and initial_action are optional; remove them if not needed.
	// provenance.ingredients is omitted because it needs absolute paths (4.6).
	request := obj{
		"schema_version": 1,
		"caller":         obj{"account_id": os.Getenv("MSL_ACCOUNT_ID")},
		"asset": obj{
			"filename":    "sample.jpeg",
			"source":      obj{"path": source},
			"destination": obj{"path": destination},
		},
		"signing": obj{
			"manifest_output": "EMBEDDED",
			"roles":           []string{"creator", "publisher"},
			"tsa_url":         "http://timestamp.digicert.com",
			"identity":        obj{"type": "NONE"},
		},
		"provenance": obj{
			"new_creation":    true,
			"created_with_ai": true,
			"digital_source_type": "http://cv.iptc.org/newscodes/digitalsourcetype/" +
				"trainedAlgorithmicMedia",
			"ai_generator": obj{"name": "Example Image Generator", "version": "3.1"},
			"initial_action": obj{
				"description": "Generated the image from a text prompt",
				"when":        "2026-08-21T05:59:00Z",
				"software_agent": obj{"name": "Example Editor", "version": "1.0",
					"operating_system": "macOS"},
			},
			"actions": []obj{
				{"action": "c2pa.edited", "description": "Adjusted exposure and contrast",
					"when":           "2026-08-21T06:00:00Z",
					"software_agent": obj{"name": "Example Editor", "version": "1.0"}},
				{"action": "c2pa.translated", "description": "Caption translated",
					"parameters": obj{"source_language": "en-US", "target_language": "fr-FR"}},
			},
		},
		"assertions": obj{
			"ai_disclosure": obj{
				"model_type":         "c2pa.types.model",
				"model_name":         "Example AI Model",
				"model_identifier":   "https://example.com/models/example",
				"content_profile":    obj{"human_oversight_level": "human_validated"},
				"scientific_domains": []string{"cs.CV", "cs.LG"},
				"metadata":           obj{"provider": "Example Provider"},
			},
			"usage_rights": obj{
				"ai_inference": obj{"permission": "constrained",
					"constraints_info": "Internal evaluation only."},
				"generative_ai_training":     obj{"permission": "prohibited"},
				"non_generative_ai_training": obj{"permission": "allowed"},
				"data_mining_and_analytics":  obj{"permission": "allowed"},
			},
			"exif": obj{"extract_from_asset": true},
			"custom": []obj{{"label": "com.example.asset-info.v1",
				"data": obj{"assetId": "42844", "campaign": "Spring launch"}}},
		},
	}

	body, err := json.Marshal(request)
	if err != nil {
		panic(err)
	}
	cRequest := C.CString(string(body))
	defer C.free(unsafe.Pointer(cRequest))

	r := C.c2pa_sign(cRequest, nil, 0, nil)
	if r == nil {
		panic("MSL returned NULL")
	}
	defer C.c2pa_free_result(r)
	if r.error_code != 0 {
		panic(fmt.Sprintf("%d: %s", int32(r.error_code), C.GoString(r.error_message)))
	}
	fmt.Println(C.GoString(r.result_json))
}

Java examples

Use OpenJDK 21 and JNA 5.17.0 or a compatible version. JNA requires an absolute path to the library file, so the examples resolve the relative path first. Java cannot change the environment of a running JVM: export C2PA_SIGNING_SERVICE_URL, C2PA_API_KEY, and C2PA_SKIP_SSL_VALIDATION=false in the shell before starting it.

11.1 Example A mandatory fields

import com.sun.jna.*;
import java.io.File;
import java.util.*;

public final class MslExample {
  public static final class SizeT extends IntegerType {
    public SizeT() { super(Native.SIZE_T_SIZE, 0, true); }
    public SizeT(long value) { super(Native.SIZE_T_SIZE, value, true); }
  }

  public static final class Result extends Structure {
    public int error_code;
    public Pointer error_message;
    public Pointer result_json;
    public Pointer outputs;
    public SizeT output_count;
    protected List<String> getFieldOrder() {
      return Arrays.asList("error_code", "error_message", "result_json",
                           "outputs", "output_count");
    }
    public Result(Pointer p) { super(p); read(); }
  }

  public interface Msl extends Library {
    int ABI_VERSION = 2;
    int c2pa_abi_version();
    // inputs is NULL here because the asset is read from a path.
    Pointer c2pa_sign(String requestJson, Pointer inputs, SizeT inputCount, String traceId);
    void c2pa_free_result(Pointer result);
  }

  static String json(String value) {
    if (value == null || value.isBlank()) {
      throw new IllegalArgumentException("Required JSON string is missing or blank");
    }
    StringBuilder escaped = new StringBuilder();
    for (int i = 0; i < value.length(); i++) {
      char ch = value.charAt(i);
      if (ch == '"' || ch == '\\') escaped.append('\\').append(ch);
      else if (ch < 0x20) escaped.append(String.format("\\u%04x", (int) ch));
      else escaped.append(ch);
    }
    return escaped.toString();
  }

  public static void main(String[] args) throws Exception {
    // MSL reads its configuration from the process environment when it loads.
    // Java cannot change the environment of a running process, so export
    // C2PA_SIGNING_SERVICE_URL, C2PA_API_KEY and C2PA_SKIP_SSL_VALIDATION=false
    // in the shell before starting the JVM.
    Msl lib = Native.load(
        new File("../rust_binary/libc2pa_rust.dylib").getAbsolutePath(),
        Msl.class, Map.of(Library.OPTION_STRING_ENCODING, "UTF-8"));
    if (lib.c2pa_abi_version() != Msl.ABI_VERSION) {
      throw new IllegalStateException("MSL ABI " + lib.c2pa_abi_version()
          + " found, " + Msl.ABI_VERSION + " required");
    }

    new File("../output").mkdirs();
    String source = new File("../input/sample.jpeg").getAbsolutePath();
    String destination = new File("../output/java_signed.jpeg").getAbsolutePath();

    String request = """
        {
          "schema_version": 1,
          "caller": { "account_id": "%s" },
          "asset": {
            "filename": "sample.jpeg",
            "source": { "path": "%s" },
            "destination": { "path": "%s" }
          },
          "signing": {
            "manifest_output": "EMBEDDED",
            "roles": ["creator"],
            "tsa_url": "http://timestamp.digicert.com"
          }
        }
        """.formatted(json(System.getenv("MSL_ACCOUNT_ID")), json(source), json(destination));

    Pointer p = lib.c2pa_sign(request, null, new SizeT(0), null);
    if (p == null) throw new IllegalStateException("MSL returned NULL");
    try {
      Result r = new Result(p);
      if (r.error_code != 0) {
        throw new IllegalStateException(r.error_code + ": "
            + (r.error_message == null ? "Unknown error" : r.error_message.getString(0, "UTF-8")));
      }
      System.out.println(r.result_json.getString(0, "UTF-8"));
    } finally {
      lib.c2pa_free_result(p);
    }
  }
}

11.2 Example B Extended standard signing with AI disclosure and custom assertions

Save this example as MslAllFieldsExample.java next to MslExample.java from Example A. It uses MslExample.Msl, MslExample.SizeT, MslExample.Result and MslExample.json; compile both classes together. Run from the java/ directory so that ../input, ../output and ../rust_binary resolve correctly.

Remove the ai_disclosure or initial_action block if you do not need it. When ai_disclosure is included, model_type is the only required child field. provenance.ingredients is omitted because it needs absolute paths to files on your host; see 4.6.

import com.sun.jna.*;
import java.io.File;
import java.util.*;

public final class MslAllFieldsExample {
  // ... same SizeT, Result and Msl declarations as MslExample (Example A) ...

  static final String REQUEST = """
      {
        "schema_version": 1,
        "caller": { "account_id": "%s" },
        "asset": {
          "filename": "sample.jpeg",
          "source": { "path": "%s" },
          "destination": { "path": "%s" }
        },
        "signing": {
          "manifest_output": "EMBEDDED",
          "roles": ["creator", "publisher"],
          "tsa_url": "http://timestamp.digicert.com",
          "identity": { "type": "NONE" }
        },
        "provenance": {
          "new_creation": true,
          "created_with_ai": true,
          "digital_source_type":
            "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
          "ai_generator": { "name": "Example Image Generator", "version": "3.1" },
          "initial_action": {
            "description": "Generated the image from a text prompt",
            "when": "2026-08-21T05:59:00Z",
            "software_agent": { "name": "Example Editor", "version": "1.0",
                                "operating_system": "macOS" }
          },
          "actions": [
            { "action": "c2pa.edited",
              "description": "Adjusted exposure and contrast",
              "when": "2026-08-21T06:00:00Z",
              "software_agent": { "name": "Example Editor", "version": "1.0" } },
            { "action": "c2pa.translated", "description": "Caption translated",
              "parameters": { "source_language": "en-US", "target_language": "fr-FR" } }
          ]
        },
        "assertions": {
          "ai_disclosure": {
            "model_type": "c2pa.types.model",
            "model_name": "Example AI Model",
            "model_identifier": "https://example.com/models/example",
            "content_profile": { "human_oversight_level": "human_validated" },
            "scientific_domains": ["cs.CV", "cs.LG"],
            "metadata": { "provider": "Example Provider" }
          },
          "usage_rights": {
            "ai_inference": { "permission": "constrained",
                              "constraints_info": "Internal evaluation only." },
            "generative_ai_training": { "permission": "prohibited" },
            "non_generative_ai_training": { "permission": "allowed" },
            "data_mining_and_analytics": { "permission": "allowed" }
          },
          "exif": { "extract_from_asset": true },
          "custom": [ { "label": "com.example.asset-info.v1",
                        "data": { "assetId": "42844", "campaign": "Spring launch" } } ]
        }
      }
      """;

  public static void main(String[] args) throws Exception {
    // ai_disclosure and initial_action are optional; remove them if not needed.
    // provenance.ingredients is omitted because it needs absolute paths (4.6).
    MslExample.Msl lib = Native.load(
        new File("../rust_binary/libc2pa_rust.dylib").getAbsolutePath(),
        MslExample.Msl.class, Map.of(Library.OPTION_STRING_ENCODING, "UTF-8"));
    if (lib.c2pa_abi_version() != MslExample.Msl.ABI_VERSION) {
      throw new IllegalStateException("MSL ABI mismatch; ABI 2 required");
    }
    new File("../output").mkdirs();
    String request = REQUEST.formatted(
        MslExample.json(System.getenv("MSL_ACCOUNT_ID")),
        MslExample.json(new File("../input/sample.jpeg").getAbsolutePath()),
        MslExample.json(new File("../output/java_all_fields.jpeg").getAbsolutePath()));

    Pointer p = lib.c2pa_sign(request, null, new MslExample.SizeT(0), null);
    if (p == null) throw new IllegalStateException("MSL returned NULL");
    try {
      MslExample.Result r = new MslExample.Result(p);
      if (r.error_code != 0) {
        throw new IllegalStateException(r.error_code + ": "
            + r.error_message.getString(0, "UTF-8"));
      }
      System.out.println(r.result_json.getString(0, "UTF-8"));
    } finally {
      lib.c2pa_free_result(p);
    }
  }
}

CAWG identity signing

CAWG identity signing adds verifiable identity information using an S/MIME Baseline Requirements credential. CAWG identity assertion signing is supported only in the production environment.

12.1 Requirements and modes

Required values are account ID, API key, and supported CAWG roles. One-step signing also needs an S/MIME credential ID and PIN, exported as C2PA_SMIME_CREDENTIAL_ID and C2PA_USER_PIN. The S/MIME certificate must be an organizational certificate that contains an Organization (O) field; otherwise signing fails with 4003.

ModeHow to request it
One-step, buffer or filec2pa_sign with signing.identity.type = CAWG_X509. MSL signs the identity assertion with the configured S/MIME credential.
Two-step, buffer or filec2pa_cawg_prepare with signing.identity.type = CAWG_X509_EXTERNAL, then c2pa_cawg_complete. Your application produces the CAWG signature (see 12.5).

12.2 CAWG roles

RoleIdentity field
creatorcawg.creator
publishercawg.publisher
contributorcawg.contributor
editorcawg.editor
producercawg.producer
sponsorcawg.sponsor

Roles are trimmed, matched case-insensitively, and de-duplicated. MSL writes each role to cawg.identity.signer_payload.role with the cawg. prefix and does not copy them into cawg.metadata. translator is not accepted and returns 4001.

12.3 Rust CAWG example A mandatory fields

This is the Example A request with signing.identity set to CAWG_X509. It uses the src/msl.rs bindings from 5.1.

mod msl;

use anyhow::Result;
use msl::Msl;
use serde_json::json;
use std::{env, fs};

// Export C2PA_SMIME_CREDENTIAL_ID and C2PA_USER_PIN before starting.
fn main() -> Result<()> {
    let msl = Msl::load("rust_binary/libc2pa_rust.dylib")?;
    fs::create_dir_all("output")?;
    let request = json!({
        "schema_version": 1,
        "caller": { "account_id": env::var("MSL_ACCOUNT_ID")? },
        "asset": {
            "filename": "sample.jpeg",
            "source": { "path": fs::canonicalize("input/sample.jpeg")? },
            "destination": { "path": env::current_dir()?.join("output/rust_cawg_signed.jpeg") }
        },
        "signing": {
            "manifest_output": "EMBEDDED",
            "roles": ["creator"],
            "tsa_url": "http://timestamp.digicert.com",
            "identity": { "type": "CAWG_X509" }
        }
    });
    let signed = msl.call("c2pa_sign", &request, &[], None)?;
    println!("Signed file: {}", signed.result["destination_path"]);
    println!("Manifest ID: {}", signed.result["manifest_id"]);
    Ok(())
}

12.4 Rust CAWG example B all fields including AI disclosure and custom assertions

Use the request from Example B (5.3) with two changes: set signing.identity to { “type”: “CAWG_X509” } and, if you want identity roles beyond the Dublin Core three, add them to signing.roles (for example “editor”). Every provenance and assertions field is supported identically in one-step and two-step CAWG signing.

12.5 Two-step CAWG signing

Use the two-step operations when your application, rather than MSL, produces the CAWG identity signature, for example with its own HSM or signing service.

  1. Call c2pa_cawg_prepare with the same request as c2pa_sign, and signing.identity set to CAWG_X509_EXTERNAL with certificate_chain_pem (the CAWG signer’s PEM chain; the leaf must be an organizational S/MIME certificate with an Organization field) and hard_binding_hash_b64 (a valid Base64 seed; MSL computes the final hard-binding hash, so a 32-byte zero value AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= is sufficient).

  2. Sign hash_to_sign_b64 with the CAWG private key, using the COSE algorithm reported in cawg_algorithm: -7 (ES256), -35 (ES384), -36 (ES512), or -37 (PS256).

  3. Call c2pa_cawg_complete with preparation_token and cawg_signature_b64. It takes no inputs.

The prepare result document contains:

FieldDescription
preparation_tokenOpaque, single-use token for c2pa_cawg_complete.
hash_to_sign_b64Base64 value to sign with the CAWG private key.
sig_structure_b64Base64 COSE Sig_Structure, for signers that need the full message.
signer_payload_cbor_b64Base64 CBOR CAWG signer payload.
assertion_jsonThe exact assertion text being signed, as a string.
cawg_algorithmCOSE algorithm for the signature.
cawg_metadata_hash_b64Base64 hash of the cawg.metadata assertion. Omitted when absent.
cawg_training_mining_hash_b64Base64 hash of the training-and-mining assertion. Omitted when no data-usage permissions are set.
ingredientsIngredient outcomes (see 4.6). Omitted when none were requested.

This example is an integration skeleton. Implement sign_with_cawg_key using your signer and supply cawg_chain.pem before running it. The supplied function deliberately raises NotImplementedError.

import os
from pathlib import Path

from msl import Msl

os.environ["C2PA_SIGNING_SERVICE_URL"] = os.environ["MSL_SIGNING_URL"]
os.environ["C2PA_API_KEY"] = os.environ["MSL_API_KEY"]
os.environ["C2PA_SKIP_SSL_VALIDATION"] = "false"


def load_cawg_certificate_chain_pem():
    """Supplied by your application: the CAWG signer's PEM certificate chain."""
    return Path("cawg_chain.pem").read_text()


def sign_with_cawg_key(hash_to_sign_b64, cawg_algorithm):
    """Supplied by your application: sign the hash with the CAWG private key
    (HSM, KMS or signing service) using the COSE algorithm cawg_algorithm,
    and return the Base64 signature."""
    raise NotImplementedError


msl = Msl("rust_binary/libc2pa_rust.dylib")
Path("output").mkdir(exist_ok=True)

# Step 1: prepare. Everything that shapes the manifest is fixed here.
prepare_request = {
    "schema_version": 1,
    "caller": {"account_id": os.environ["MSL_ACCOUNT_ID"]},
    "asset": {
        "filename": "sample.jpeg",
        "source": {"path": str(Path("input/sample.jpeg").resolve())},
        "destination": {"path": str(Path("output/python_cawg_two_step.jpeg").resolve())},
    },
    "signing": {
        "manifest_output": "EMBEDDED",
        "roles": ["creator"],
        "tsa_url": "http://timestamp.digicert.com",
        "identity": {
            "type": "CAWG_X509_EXTERNAL",
            "certificate_chain_pem": load_cawg_certificate_chain_pem(),
            # MSL computes the final hard-binding hash, so a 32-byte zero seed is enough.
            "hard_binding_hash_b64": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
        },
    },
}
prepared, _ = msl.call("c2pa_cawg_prepare", prepare_request)

# Step 2: sign hash_to_sign_b64 with your own key.
signature_b64 = sign_with_cawg_key(prepared["hash_to_sign_b64"], prepared["cawg_algorithm"])

# Step 3: complete. The token is single use; no inputs are taken.
result, _ = msl.call("c2pa_cawg_complete", {
    "schema_version": 1,
    "preparation_token": prepared["preparation_token"],
    "cawg_signature_b64": signature_b64,
})
print("Signed file:", result["destination_path"])
print("Manifest ID:", result["manifest_id"])
  • c2pa_cawg_complete takes only preparation_token, cawg_signature_b64, and the trace ID. tsa_url, actions, metadata, ingredients, custom assertions, and placement are fixed at prepare time.

  • A preparation token is single use and expires after C2PA_CAWG_CONTEXT_EXPIRY_SECS seconds (default 300). MSL keeps at most 100 pending preparations and evicts the oldest when the limit is reached. An unknown or expired token returns 4000.

  • MSL verifies the signature against sig_structure_b64 and the certificate chain before embedding it. A signature that does not verify returns 5022.

  • For a path source the signed asset is written to asset.destination.path when c2pa_cawg_complete runs; for an input source it is returned as the asset output.

  • Release each result with c2pa_free_result once you have copied out what you need. The Python and Node.js bindings above do this for you.

Sidecar validation

c2pa_validate_sidecar checks that a detached Manifest Store is valid for an asset, under the same trust policy as signing. Both sources accept {“input”: …} only, and both buffers must be non-empty. asset.filename is used only for media-type detection.

{
  "schema_version": 1,
  "asset":   { "filename": "photo.jpg", "source": { "input": "asset" } },
  "sidecar": { "input": "sidecar" }
}

The following response examples are abbreviated; the first omits the manifest-store contents. A sidecar that is evaluated and found invalid is a successful call (error_code 0) with “valid”: false:

{ "schema_version": 1, "valid": true, "validation_state": "trusted", "manifest_store": { … } }
{ "schema_version": 1, "valid": false,
  "failure_code": "assertion.dataHash.mismatch", "failure_reason": "…" }
  • validation_state is trusted, valid, or untrusted. Only trusted means the signer is on the trust list. valid means the signature and hard binding verified but trust was not established (for example with C2PA_VERIFY_TRUST=false). untrusted means the credential is off the trust list and the relaxed policy accepted it. Require trusted if you need trust assurance.

  • failure_code is a c2pa-rs status code or one of sidecar.unreadable, sidecar.noActiveManifest, sidecar.untrusted, sidecar.invalid, cawg.identity.unverified.

  • By default the policy is strict: a credential missing from the trust list is rejected as sidecar.untrusted. With SKIP_C2PA_PUBLIC_TRUST_LIST_CHECK=true it is accepted and reported as untrusted. Revoked, expired, or invalid credentials and any signature or hard-binding mismatch are always rejected, and a CAWG identity assertion whose signature was not verified is rejected as cawg.identity.unverified even in relaxed mode.

  • Validation makes no outbound OCSP or AIA request unless C2PA_OCSP_FETCH=true, and a supplied sidecar is never resolved through a remote manifest URL.

  • For PDF assets, request SIDECAR output and retain the returned store alongside the unchanged PDF. Validate the sidecar against that PDF before using or distributing the pair.

Situation (call itself fails)CodeMessage
Malformed request, missing or unreferenced input, empty asset or sidecar, {“path”: …} source, unsupported media type4000Parameter-specific
Non-UTF-8 request, input name, or trace ID4002Parameter-specific
Sidecar over 16 MiB, rejected before parsing4000sidecar data too large (limit 16777216 bytes)
Manifest store JSON over 8 MiB (never truncated)4000manifest store too large (limit 8388608 bytes)
Strict mode and the shared trust context cannot be built (fails closed)5000trust context unavailable
Unexpected internal failure5000Message
import os
from pathlib import Path

from msl import Msl

os.environ["C2PA_SKIP_SSL_VALIDATION"] = "false"

msl = Msl("rust_binary/libc2pa_rust.dylib")

asset = Path("input/photo.jpg").read_bytes()
sidecar = Path("input/photo.c2pa").read_bytes()

result, _ = msl.call("c2pa_validate_sidecar", {
    "schema_version": 1,
    "asset": {"filename": "photo.jpg", "source": {"input": "asset"}},
    "sidecar": {"input": "sidecar"},
}, inputs={"asset": asset, "sidecar": sidecar})

if result["valid"]:
    print("Valid sidecar, state:", result["validation_state"])  # require "trusted" for trust
else:
    print("Rejected:", result["failure_code"], "-", result["failure_reason"])

Read the current validation assessment from top-level validation_results.activeManifest and ingredientDeltas. An ingredient assertion’s validationResults describes the assessment recorded when that ingredient was imported. Use the current assessment to determine present validity and trust, and retain the recorded assessment for provenance history.

Verification

c2patool -d output/sample_signed.jpeg trust \
  --trust_anchors=https://raw.githubusercontent.com/c2pa-org/conformance-public/refs/heads/main/trust-list/C2PA-TRUST-LIST.pem

Timestamp integrity and timestamp trust are separate results. timeStamp.validated confirms a matching timestamp message digest; timeStamp.untrusted means the timestamp authority was not trusted by that reader. Configure the reader’s trust policy for your use case. OCSP messages describe the reader’s revocation-check behaviour.

Use c2patool’s trust subcommand to evaluate signer trust. A trusted asset reports validation_state=Trusted, a trusted signing credential, a valid claim signature and a matching asset binding. Review the current failure array as well as the overall state. Configure c2patool separately from the MSL application.

14.1 Tamper test

To check hard-binding validation, modify quantization data in a disposable copy of a signed JPEG while preserving its manifest and file structure. Appending bytes alone does not reliably change the bound content for every format.

python3 - <<'PY'
from pathlib import Path
source = Path("output/sample_signed.jpeg")
data = bytearray(source.read_bytes())
marker = data.find(b"\xff\xdb")
if marker < 0 or marker + 5 >= len(data):
    raise SystemExit("No usable JPEG quantization marker found")
data[marker + 5] ^= 1
Path("output/sample_signed_tampered.jpeg").write_bytes(data)
PY
c2patool -d output/sample_signed_tampered.jpeg trust

Inspect the current failure results for assertion.dataHash.mismatch. Signing an asset with an invalid existing manifest returns 4003.

Errors and troubleshooting

ConditionResultHandling
Invalid API key loaded at application startup5020 and HTTP 401 wrong_tokenCorrect C2PA_API_KEY in the application’s startup environment and restart the application before retrying.
Signing still succeeds after replacing the API key while the application is runningMSL continues using the previously loaded keyRestart the application with the replacement key configured.
An environment or credential configuration change has no effectMSL continues using the values it first loadedUpdate the application’s startup environment and restart every affected process.
Empty or invalid API key at process startup5020; HTTP 401 wrong_tokenSupply a valid, non-empty key in the startup environment and restart the application.
Signing service unreachable5020, Failed to send … requestCheck C2PA_SIGNING_SERVICE_URL (the unset default is a local development address), network access, and TLS settings.
Existing output5022, destination existsUse a new path or remove the old file.
Invalid role, such as translator or a CAWG-only role in standard signing4001Use roles allowed for the identity type (see 4.1 and 12.2).
Invalid JSON, unknown field at any level, wrong type, or schema_version missing or not 14000Correct the request document. The message names the unknown field and the accepted fields.
Input referenced but not supplied, supplied but not referenced, duplicate or empty input name4000Make the inputs array and the {"input": …} references match exactly.
asset.destination set for an input source, or missing for a path source4000Use destination only with a path source.
Request over 8 MiB4000Reduce the request. Pass large data as inputs or paths, not inline.
ai_disclosure present but model_type is missing or not in the model-type vocabulary4000Include a value listed in 4.7, such as c2pa.types.model.
human_oversight_level not recognised, scientific_domains not a non-empty array of arXiv categories, or metadata not an object4000Use the values in 4.7.
digital_source_type not in the accepted vocabulary4000Use a value listed in 4.3.
permission is constrained without non-empty constraints_info4000Provide a non-empty constraints_info for constrained permission. Omit constraints_info for allowed and prohibited.
trace_id is not a canonical UUID v44000Pass NULL or a canonical UUID v4 (see 4.9).
A string argument is not valid UTF-84002Encode all strings as UTF-8.
Action label is managed by MSL, deprecated, or unsupported, or a conditional action lacks required fields4000Use a declarable action and supply the required fields (see 4.4).
Invalid assertions.custom: not an array, invalid or reserved or repeated label, extra keys, or over the size, count, or nesting limits4000Correct the array (see 4.8).
Ingredient path is relative or duplicated, or the file is missing or exceeds 512 MiB4000Use distinct absolute paths to readable regular files no larger than 512 MiB.
More than one parentOf ingredient, or a parentOf ingredient for an asset that already has provenance4000Declare the other ingredients as componentOf or inputTo.
SIDECAR requested for an asset that already carries an embedded manifest4000Request EMBEDDED or BOTH.
previous_sidecar was issued for different asset bytes4003; assertion.dataHash.mismatchSupply the sidecar issued for these asset bytes, or omit previous_sidecar.
Existing manifest on the asset fails validation4003Check the asset with c2patool.
S/MIME certificate has no Organization (O) field4003Use an organizational S/MIME certificate.
Unknown or expired CAWG preparation token4000Call prepare again and complete within C2PA_CAWG_CONTEXT_EXPIRY_SECS.
CAWG signature does not verify5022Sign hash_to_sign_b64 with the private key for the supplied chain using cawg_algorithm.
Signing service rate limit reached4029Retry with backoff.
Bindings declare the ABI 1 argument list, C2paSignedResult, or C2paPrepareResultMissing symbol, undefined behaviour, or misreported errorsRebuild against ABI 2 (3.2). Check c2pa_abi_version() before the first call.
dyld: Library not loaded when a C or Go program starts on macOSStart-up failureRewrite the install name as described in 1.1.
Missing input or libraryLocal path or load errorValidate paths and architecture.
Modified signed fileassertion.dataHash.mismatchTreat the asset as changed.
Unsigned target is its only ingredient and new_creation=true4000Use new_creation=false for the self-parent/opened flow.
Target appears alongside another ingredient with distinct IDs4000Remove the target from the ingredient list or use the target as its only self-parent.
Empty binary asset passed to c2pa_sign4003Provide a non-empty supported asset. Sidecar validation rejects empty buffers with 4000.
Claim-generator value rejected by the service5020; HTTP 400 invalid_requestRetain the default DigiCert Content Trust Manager claim-generator name.
Required library-version header missing5020; HTTP 400 invalid_requestLeave C2PA_SEND_DTM_MSL_HEADER at its default true.

Platform and tool compatibility

ComponentVersion or platformIntegration notes
macOS libraryarm64 and x86_64Use the .dylib package matching the application architecture. See section 1.1 for C and Go linking.
RustRust 1.89.0; libloading 0.8; anyhow 1; serde_json 1Load the platform library with libloading and call the C-compatible interface.
PythonPython 3.9.6 or laterUse the standard ctypes module.
CApple clang on arm64 or x86_64Include c2pa_msl.h and link the native library.
C#.NET 8 or laterUse P/Invoke and System.Text.Json. The project commands below target .NET 10.
Node.jsNode.js 26.0.0; Koffi 3.3.6Use Koffi to call the C-compatible interface.
GoGo 1.26.7 on darwin/arm64Use cgo and the C header.
JavaOpenJDK 21; JNA 5.17.0Use JNA to call the C-compatible interface.
c2patool0.28.4Use detailed inspection and the trust subcommand to verify generated assets.

References