Media Signing Library
71 minute read
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.
| Category | Supported media types |
|---|---|
| Still image | image/jpeg, image/png, image/x-adobe-dng, image/heic, image/heif, image/tiff, image/webp, image/svg+xml, image/gif, image/jxl, image/avif |
| Video | video/mp4, video/x-msvideo, video/quicktime |
| Audio | audio/wav, audio/mp4, audio/flac, audio/mpeg |
| Document | application/pdf - use SIDECAR manifest output |
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.
| Surface | Best use | Result |
|---|---|---|
c2pa_sign with a path source | Backend services and large assets | Signed asset written to asset.destination.path; destination_path in the result document |
c2pa_sign with an input source | Byte-oriented pipelines | Output buffer named asset |
c2pa_sign with signing.identity.type = CAWG_X509 | One-step CAWG identity signing with the configured S/MIME credential | Same as standard signing |
c2pa_cawg_prepare + c2pa_cawg_complete | Applications that produce the CAWG identity signature with their own signer | Prepare result document, then the same result as c2pa_sign |
c2pa_validate_sidecar | Checking a detached Manifest Store against an asset | Result 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 system | Binary | Typical path |
|---|---|---|
| macOS | libc2pa_rust.dylib | rust_binary/libc2pa_rust.dylib |
| Linux | libc2pa_rust.so | rust_binary/libc2pa_rust.so |
| Windows | c2pa_rust.dll | rust_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>
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 variable | Set explicitly | Default | Purpose |
|---|---|---|---|
C2PA_API_KEY | Yes | None | API key for the signing service. Supply a non-empty key for the account used in the request. |
C2PA_SIGNING_SERVICE_URL | Yes | Local development URL | Signing-service endpoint. For production, use https://one.digicert.com/documentmanager or the production URL provided for your environment. |
C2PA_SKIP_SSL_VALIDATION | Yes | true | Set false to validate the signing service’s TLS certificate. |
SKIP_C2PA_PUBLIC_TRUST_LIST_CHECK | No | false | true 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_NAME | No | DigiCert Content Trust Manager | Claim-generator name. Retain the default for DigiCert production signing. The version comes from the library. |
C2PA_PRODUCT_NAME, C2PA_PRODUCT_VERSION | No | DigiCert Content Trust Manager; library version | Product name and version used by the library. |
C2PA_SMIME_CREDENTIAL_ID | For CAWG | None | S/MIME credential used for the CAWG identity signature. |
C2PA_USER_PIN | For CAWG | None | PIN for the S/MIME credential. |
C2PA_TSA_URL | No | http://timestamp.digicert.com | TSA used when signing.tsa_url is absent or blank. |
C2PA_TSA_TIMEOUT_SECS | No | 30 | Timeout for each TSA request, in seconds. Must be greater than 0. |
C2PA_DISABLE_DEFAULT_TSA | No | false | true applies no timestamp when signing.tsa_url is absent or blank. An explicit signing.tsa_url is still used. |
C2PA_CAWG_CONTEXT_EXPIRY_SECS | No | 300 | Lifetime of a two-step CAWG preparation token, in seconds. |
C2PA_VERIFY_TRUST | No | true | Evaluate trust of existing manifests. With false, sidecar validation reports valid rather than trusted. |
C2PA_VERIFY_TIMESTAMP_TRUST | No | true | Evaluate trust of timestamps in existing manifests. |
C2PA_OCSP_FETCH | No | false | Fetch OCSP responses for the signing certificate and staple them into the signature. |
C2PA_INGREDIENT_OCSP_FETCH | No | false | Fetch 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_FETCH | No | true | Allow resolving remote manifest URLs found in assets. A supplied sidecar is never resolved remotely. |
C2PA_SEND_DTM_MSL_HEADER | No | true | Include the library version in the msl-version header. Leave enabled for DigiCert production signing. |
C2PA_ENVIRONMENT | No | prod | Environment 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_URL | No | None | Remote 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_SECS | No | 86400 | How long a fetched trust list is cached. |
C2PA_TRUST_LIST_FAILURE_RETRY_SECS | No | 300 | Wait 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_PATH | No | Built-in thumbnail | Path to a file that replaces the built-in thumbnail for that media category. Blank or missing paths are ignored. |
C2PA_LOG_LEVEL | No | info | Log 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.
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:
| Language | Environment-setting interface |
|---|---|
| Python | os.environ |
| Node.js | process.env |
| Go | os.Setenv |
| Rust | std::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
- Sign in to DigiCert ONE Content Trust Manager.
- Open Client Tool repository.
- Download the Media Signing Library package for the application’s operating system and processor architecture.
- Keep the accompanying
c2pa_msl.hheader with the project.
Python loads the binary directly; it does not compile the header.
| Operating system | Library filename |
|---|---|
| macOS | libc2pa_rust.dylib |
| Linux | libc2pa_rust.so |
| Windows | c2pa_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.hintoinclude/. - Place an unsigned JPEG at
input/sample.jpeg. - Save the Python program from Step 4 as
sign_media.pyin 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"
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.
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.
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
| Function | Purpose | Returns |
|---|---|---|
c2pa_abi_version | Reports the ABI version (2). Never allocates. | uint32_t |
c2pa_library_info | Reports ABI version, supported request schema versions, and library version. | C2paResult * with result_json |
c2pa_sign | Standard 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_prepare | Step 1 of two-step CAWG signing. | C2paResult * with the preparation token and hash to sign |
c2pa_cawg_complete | Step 2 of two-step CAWG signing. | Same as c2pa_sign |
c2pa_validate_sidecar | Checks a detached Manifest Store against an asset. | C2paResult * with valid |
c2pa_free_result | Releases 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_resultfrees 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 whoseschema_versionis 1. Unknown fields are rejected at every level, so a typo fails instead of being ignored. Optional fields may be omitted or null. A blankcaller.user_idorsigning.tsa_urlis treated as absent.Inputs. inputs may be
NULLonly wheninput_countis 0. Every input needs a non-empty, unique, UTF-8 name; data may beNULLonly 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_codeis 0,error_messageisNULL, andresult_jsonholds the result document with"schema_version": 1. On failureerror_codeis non-zero,error_messageexplains why, andresult_jsonand outputs areNULL.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_VERSIONchanges only if a signature or layout ever has to.
3.4 Result structure
| Field | Type | Description |
|---|---|---|
error_code | int32_t | 0 on success. An error code from 3.5 on failure. |
error_message | char * | NULL on success. Human-readable message on failure. |
result_json | char * | NULL on failure. The versioned result document on success (see 4.10 and 13). |
outputs | C2paOutput * | Binary artifacts, looked up by name. NULL when output_count is 0. |
output_count | size_t | Number 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
| Code | Name | Meaning |
|---|---|---|
| 0 | SUCCESS | The operation completed. |
| 4000 | INVALID_PARAMETER | Malformed request, unknown field, bad input, or rejected value. |
| 4001 | INVALID_ROLE | A role is not one of the supported roles for the requested identity type. |
| 4002 | INVALID_ENCODING | A string is not valid UTF-8. |
| 4003 | VALIDATION_FAILED | Manifest or certificate validation prevented signing, for example the asset’s existing manifest failed validation or the S/MIME certificate has no Organization (O) field. |
| 4029 | RATE_LIMITED | The signing service rejected the call with HTTP 429. |
| 5000 | INTERNAL_ERROR | Unexpected failure, including a caught panic. |
| 5001 | CONFIGURATION_ERROR | Missing or invalid library configuration, such as no API key. |
| 5020 | SIGNING_SERVICE_ERROR | The signing service returned an error or was unreachable. |
| 5021 | CERTIFICATE_FETCH_ERROR | The signing certificate could not be fetched. |
| 5022 | SIGNING_FAILED | The 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 1 | ABI 2 |
|---|---|
c2pa_sign_content, c2pa_sign_content_from_path | c2pa_sign with asset.source = input / path |
c2pa_sign_content_with_cawg_identity, c2pa_sign_content_with_cawg_identity_from_path | c2pa_sign with signing.identity.type = CAWG_X509 |
c2pa_prepare_cawg_signing, c2pa_prepare_cawg_signing_from_path | c2pa_cawg_prepare |
c2pa_complete_cawg_signing, c2pa_complete_cawg_signing_from_path | c2pa_cawg_complete |
c2pa_validate_sidecar(asset, …, sidecar, …) | c2pa_validate_sidecar with a request document |
C2paSignedResult, C2paPrepareResult, C2paSidecarValidationResult | C2paResult |
c2pa_free_prepare_result, c2pa_free_sidecar_validation_result | c2pa_free_result |
file_data / file_data_len, input_path, output_path | asset.source, asset.destination |
filename, account_id, user_id, tsa_url | asset.filename, caller.account_id, caller.user_id, signing.tsa_url |
roles_csv | signing.roles (array) |
requested_output_mode (1 / 2 / 3) | signing.manifest_output (EMBEDDED / SIDECAR / BOTH) |
previous_sidecar_data / previous_sidecar_data_len | provenance.previous_sidecar |
cawg_certificate_chain_pem, hard_binding_hash_b64 | signing.identity (CAWG_X509_EXTERNAL) |
additional_actions_json | provenance.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, createdWithAi | provenance.new_creation, digital_source_type, created_with_ai |
signing_metadata_json.softwareAgent, softwareVersion | provenance.ai_generator.name, provenance.ai_generator.version |
signing_metadata_json.editedWithAi | Removed; the library now rejects it. Declare AI editing with an action that carries digital_source_type (for example, compositeWithTrainedAlgorithmicMedia). |
signing_metadata_json.initialAction | provenance.initial_action (softwareAgent → software_agent, ingredientPaths → ingredient IDs in ingredients) |
signing_metadata_json.ingredients | provenance.ingredients (path → source.path) |
signing_metadata_json.aiDisclosure | assertions.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.includeExifMetadata | assertions.exif.extract_from_asset |
custom_assertions_json | assertions.custom |
trace_id | trace_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_path | destination_path |
Result signed_data, signed_data_len, sidecar_data | Outputs 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": [ … ]
}
}
| Field | Required | Meaning |
|---|---|---|
caller.account_id | Yes | Account the signature is made for. |
caller.user_id | No | User within the account. When absent, the API key’s context is used. |
asset.filename | Yes | Name used for media-type detection and as the manifest title. |
asset.source | Yes | {“input”: …} signs bytes and returns the asset output. {“path”: …} signs a file. |
asset.destination.path | Path source only | Where 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_output | Yes | EMBEDDED, SIDECAR, or BOTH. See 4.2. |
signing.roles | Yes | Non-empty list of roles. See 4.1. |
signing.tsa_url | No | Timestamp 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.type | No | NONE (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.* | No | Origin and processing history. See 4.3 to 4.7. |
assertions.* | No | Assertions 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_output | Signed asset | sidecar output |
|---|---|---|
EMBEDDED | Manifest Store embedded | Absent |
SIDECAR | Unmodified | Detached Manifest Store (a .c2pa payload) |
BOTH | Manifest Store embedded | The same store, also detached |
Any other value fails with 4000.
SIDECARis rejected for an asset that already carries an embedded manifest, because it would discard that provenance. RequestEMBEDDEDorBOTHinstead.Read actual_placement and asset_modified_from_input in the result rather than assuming the request was honoured.
SIDECARoutput 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(inSIDECARmode, a byte-identical copy of the input) and return the detached store as the sidecar output. Persist it as<asset stem>.c2paif 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
| Field | Type | Description |
|---|---|---|
provenance.new_creation | boolean | Asserts 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_type | string | IPTC / C2PA digital source type URI for the first action (see the table below). Overridden by created_with_ai = true. |
provenance.created_with_ai | boolean | The asset was created with AI (new assets only). Results in trainedAlgorithmicMedia. |
provenance.ai_generator | object | name and version of the software used for AI-assisted creation. Used only when created_with_ai is true. |
provenance.initial_action | object | Metadata for the first action. See 4.5. |
provenance.ingredients[] | array | Source files recorded as C2PA ingredients. See 4.6. |
provenance.actions[] | array | Processing actions. See 4.4. |
assertions.exif.extract_from_asset | boolean | Copy 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_inference | object | permission: 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_training | object | Same shape. |
assertions.usage_rights.data_mining_and_analytics | object | Same shape. |
assertions.usage_rights.non_generative_ai_training | object | Same shape. |
assertions.ai_disclosure | object | c2pa.ai-disclosure assertion. See 4.7. |
assertions.custom[] | array | Caller-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.
| Value | Description |
|---|---|
http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture | Digital capture |
http://cv.iptc.org/newscodes/digitalsourcetype/computationalCapture | Computational capture |
http://cv.iptc.org/newscodes/digitalsourcetype/negativeFilm | Negative film |
http://cv.iptc.org/newscodes/digitalsourcetype/positiveFilm | Positive film |
http://cv.iptc.org/newscodes/digitalsourcetype/print | |
http://cv.iptc.org/newscodes/digitalsourcetype/humanEdits | Human edits |
http://cv.iptc.org/newscodes/digitalsourcetype/algorithmicallyEnhanced | Algorithmically enhanced |
http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation | Digital creation |
http://cv.iptc.org/newscodes/digitalsourcetype/dataDrivenMedia | Data-driven media |
http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia | Trained algorithmic media |
http://cv.iptc.org/newscodes/digitalsourcetype/algorithmicMedia | Algorithmic media |
http://cv.iptc.org/newscodes/digitalsourcetype/screenCapture | Screen capture |
http://cv.iptc.org/newscodes/digitalsourcetype/virtualRecording | Virtual recording |
http://cv.iptc.org/newscodes/digitalsourcetype/composite | Composite |
http://cv.iptc.org/newscodes/digitalsourcetype/compositeCapture | Composite capture |
http://cv.iptc.org/newscodes/digitalsourcetype/compositeSynthetic | Composite synthetic |
http://cv.iptc.org/newscodes/digitalsourcetype/compositeWithTrainedAlgorithmicMedia | Composite with trained algorithmic media |
http://c2pa.org/digitalsourcetype/empty | Empty (C2PA) |
http://c2pa.org/digitalsourcetype/trainedAlgorithmicData | Trained 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
| Field | Type | Requirement | Description |
|---|---|---|---|
action | string | Required | Action label. |
description | string | Optional | Description of the action, up to 4096 characters. |
when | string | Optional | Event 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_agent | object | Optional | Software that performed the action: name (required, non-blank), version, and operating_system. |
digital_source_type | string | Optional | Accepted digital source type URI for this action (see 4.3). |
ingredients | array of strings | Conditional | IDs declared in provenance.ingredients. Links the action to those ingredients. Required for c2pa.mixed and c2pa.removed. |
parameters.source_language, parameters.target_language | string | Conditional | Valid BCP 47 language tags. Required for c2pa.translated; rejected on other actions. |
Unknown fields, wrong types, and invalid values fail with 4000.
Action labels
| Category | Labels | Rule |
|---|---|---|
| Declarable | c2pa.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.unknown | Accepted. |
| Conditional | c2pa.translated | Requires parameters.source_language and parameters.target_language. |
| Conditional | c2pa.mixed | Requires ingredients that select audio componentOf ingredients. |
| Conditional | c2pa.removed | Requires ingredients that select componentOf ingredients with a resolvable manifest. |
| Managed by MSL | c2pa.created, c2pa.opened, c2pa.placed | Rejected 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 supported | c2pa.redacted, c2pa.watermarked.bound, c2pa.watermarked.unbound | Rejected. |
| Deprecated | c2pa.color_adjustments, c2pa.watermarked, c2pa.copied, c2pa.formatted, c2pa.version_updated, c2pa.printed, c2pa.managed, c2pa.produced, c2pa.saved | Rejected. C2PA 2.4 no longer allows these labels to be written. |
| Not enabled | font.charactersAdded, font.charactersDeleted, font.charactersModified, font.createdFromVariableFont, font.edited, font.hinted, font.merged, font.openTypeFeatureAdded, font.openTypeFeatureModified, font.openTypeFeatureRemoved, font.subset | Rejected until font-asset signing is supported. |
| Unknown | Any other label | Rejected. |
allActionsIncludedis always emitted. On thec2pa.openedpath it is always true. On thec2pa.createdpath it is true when at least one additional action is provided (orcreated_with_aiadds an AI-related action) and false otherwise.Every signing path re-checks the assembled manifest immediately before signing and aborts with
VALIDATION_FAILEDrather than produce a non-conformant manifest (everyc2pa.actions*assertion must carry a booleanallActionsIncluded; when the only action isc2pa.opened, the flag must be true).MSL no longer restricts which ingredients a
c2pa.transcodedaction may reference. The bundled c2pa-rs 0.90.21 reportsassertion.action.ingredientMismatchfor a transcoded action that references a non-parentOfingredient; 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. Forc2pa.opened, omit it or select only the explicitparentOfingredient.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" }
]
}
}
| Field | Type | Requirement | Description |
|---|---|---|---|
source | object | Required | {"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. |
relationship | string | Optional | parentOf (default), componentOf, or inputTo. |
id | string | Optional | Unique, 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
parentOfingredient; remember thatparentOfis the default. If the asset being signed already has C2PA provenance, declare ingredients ascomponentOforinputTo.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.componentOfingredients are referenced by onec2pa.placedaction that MSL adds.inputToingredients get no automatic action.When the unsigned target is its only ingredient, set
new_creation=false. MSL records the target asparentOfand selectsc2pa.opened. Settingnew_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"] }
]
| status | included | Meaning |
|---|---|---|
| included | true | Included with its C2PA manifest store. validation_codes is present if reported. |
| unsigned | true | The file has no C2PA manifest. Included with its hash only. |
unsupported_format | true | C2PA cannot read this format. Included with its hash only. |
invalid_manifest | true | The 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.
| Situation | Result |
|---|---|
More than one parentOf entry (remember the default) | Rejected (4000) |
Target already has C2PA provenance and a different explicit parentOf is supplied | Rejected; declare it componentOf or inputTo |
Target has no provenance and an explicit parentOf is included | It replaces the implicit self-parent; the first action is c2pa.opened |
| Unsigned target is its only ingredient | Set new_creation=false for parentOf / c2pa.opened. new_creation=true returns 4000. |
Target is its only ingredient and previous_sidecar is supplied | The matching sidecar supplies the parent manifest. A sidecar for different asset bytes returns 4003. |
| Self-reference plus any other ingredient | Rejected: 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.
| Field | Requirement | Accepted values |
|---|---|---|
model_type | Required when ai_disclosure is present | One 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_name | Optional | Any free-text string, for example Acme Creative Studio v3.2. |
model_identifier | Optional | Any string that uniquely identifies the model: a URI, PURL, UUID, or other identifier. |
content_profile.human_oversight_level | Optional | fully_autonomous, prompt_guided, or human_validated. |
scientific_domains | Optional | A non-empty array of arXiv category identifiers, for example cs.AI, cs.CV, cs.CL, cs.LG. |
metadata | Optional | An arbitrary JSON object. Nested objects are supported; arrays and primitive values are rejected. |
human_oversight_level | Meaning |
|---|---|
fully_autonomous | The AI model produced the content without human review. |
prompt_guided | A human provided prompts or direction, but did not review the output. |
human_validated | A 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" } }
]
}
}
| Field | Type | Requirement | Description |
|---|---|---|---|
| label | string | Required | Namespaced 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. |
| data | any JSON value | Required | Assertion 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 value | Behaviour |
|---|---|
NULL | MSL 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 forms | The call fails with 4000; nothing is signed. |
| Not valid UTF-8 | The 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 / output | Meaning |
|---|---|
manifest_id | Signing reference returned by MSL. To select the active C2PA claim, use the active_manifest label returned by your reader. |
actual_placement | EMBEDDED, SIDECAR, or BOTH. Read this rather than inferring placement from the outputs. |
asset_modified_from_input | Whether the signed asset differs from the input. |
destination_path | Where a path source was written. Absent for an input source. |
ingredients | Per-ingredient outcomes. Present only when ingredients were requested. |
Output asset | Signed asset bytes for an input source (always present, may be empty). |
Output sidecar | Detached 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
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.SetEnvironmentVariabledoes not change the native process environment that MSL reads. ExportC2PA_SIGNING_SERVICE_URL,C2PA_API_KEY, andC2PA_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.
| Mode | How to request it |
|---|---|
| One-step, buffer or file | c2pa_sign with signing.identity.type = CAWG_X509. MSL signs the identity assertion with the configured S/MIME credential. |
| Two-step, buffer or file | c2pa_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
| Role | Identity field |
|---|---|
| creator | cawg.creator |
| publisher | cawg.publisher |
| contributor | cawg.contributor |
| editor | cawg.editor |
| producer | cawg.producer |
| sponsor | cawg.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.
Call
c2pa_cawg_preparewith the same request asc2pa_sign, andsigning.identityset toCAWG_X509_EXTERNALwithcertificate_chain_pem(the CAWG signer’s PEM chain; the leaf must be an organizational S/MIME certificate with an Organization field) andhard_binding_hash_b64(a valid Base64 seed; MSL computes the final hard-binding hash, so a 32-byte zero value AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= is sufficient).Sign
hash_to_sign_b64with the CAWG private key, using the COSE algorithm reported incawg_algorithm: -7 (ES256), -35 (ES384), -36 (ES512), or -37 (PS256).Call
c2pa_cawg_completewithpreparation_tokenandcawg_signature_b64. It takes no inputs.
The prepare result document contains:
| Field | Description |
|---|---|
preparation_token | Opaque, single-use token for c2pa_cawg_complete. |
hash_to_sign_b64 | Base64 value to sign with the CAWG private key. |
sig_structure_b64 | Base64 COSE Sig_Structure, for signers that need the full message. |
signer_payload_cbor_b64 | Base64 CBOR CAWG signer payload. |
assertion_json | The exact assertion text being signed, as a string. |
cawg_algorithm | COSE algorithm for the signature. |
cawg_metadata_hash_b64 | Base64 hash of the cawg.metadata assertion. Omitted when absent. |
cawg_training_mining_hash_b64 | Base64 hash of the training-and-mining assertion. Omitted when no data-usage permissions are set. |
| ingredients | Ingredient 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_completetakes onlypreparation_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_SECSseconds (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_b64and 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.pathwhenc2pa_cawg_completeruns; for an input source it is returned as the asset output.Release each result with
c2pa_free_resultonce you have copied out what you need. The Python andNode.jsbindings 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_stateis 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 withC2PA_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_codeis a c2pa-rs status code or one ofsidecar.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. WithSKIP_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 ascawg.identity.unverifiedeven 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
SIDECARoutput 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) | Code | Message |
|---|---|---|
| Malformed request, missing or unreferenced input, empty asset or sidecar, {“path”: …} source, unsupported media type | 4000 | Parameter-specific |
| Non-UTF-8 request, input name, or trace ID | 4002 | Parameter-specific |
| Sidecar over 16 MiB, rejected before parsing | 4000 | sidecar data too large (limit 16777216 bytes) |
| Manifest store JSON over 8 MiB (never truncated) | 4000 | manifest store too large (limit 8388608 bytes) |
| Strict mode and the shared trust context cannot be built (fails closed) | 5000 | trust context unavailable |
| Unexpected internal failure | 5000 | Message |
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
| Condition | Result | Handling |
|---|---|---|
| Invalid API key loaded at application startup | 5020 and HTTP 401 wrong_token | Correct 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 running | MSL continues using the previously loaded key | Restart the application with the replacement key configured. |
| An environment or credential configuration change has no effect | MSL continues using the values it first loaded | Update the application’s startup environment and restart every affected process. |
| Empty or invalid API key at process startup | 5020; HTTP 401 wrong_token | Supply a valid, non-empty key in the startup environment and restart the application. |
| Signing service unreachable | 5020, Failed to send … request | Check C2PA_SIGNING_SERVICE_URL (the unset default is a local development address), network access, and TLS settings. |
| Existing output | 5022, destination exists | Use a new path or remove the old file. |
| Invalid role, such as translator or a CAWG-only role in standard signing | 4001 | Use 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 1 | 4000 | Correct 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 name | 4000 | Make the inputs array and the {"input": …} references match exactly. |
asset.destination set for an input source, or missing for a path source | 4000 | Use destination only with a path source. |
| Request over 8 MiB | 4000 | Reduce 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 vocabulary | 4000 | Include 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 object | 4000 | Use the values in 4.7. |
digital_source_type not in the accepted vocabulary | 4000 | Use a value listed in 4.3. |
permission is constrained without non-empty constraints_info | 4000 | Provide a non-empty constraints_info for constrained permission. Omit constraints_info for allowed and prohibited. |
trace_id is not a canonical UUID v4 | 4000 | Pass NULL or a canonical UUID v4 (see 4.9). |
| A string argument is not valid UTF-8 | 4002 | Encode all strings as UTF-8. |
| Action label is managed by MSL, deprecated, or unsupported, or a conditional action lacks required fields | 4000 | Use 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 limits | 4000 | Correct the array (see 4.8). |
| Ingredient path is relative or duplicated, or the file is missing or exceeds 512 MiB | 4000 | Use 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 provenance | 4000 | Declare the other ingredients as componentOf or inputTo. |
SIDECAR requested for an asset that already carries an embedded manifest | 4000 | Request EMBEDDED or BOTH. |
previous_sidecar was issued for different asset bytes | 4003; assertion.dataHash.mismatch | Supply the sidecar issued for these asset bytes, or omit previous_sidecar. |
| Existing manifest on the asset fails validation | 4003 | Check the asset with c2patool. |
| S/MIME certificate has no Organization (O) field | 4003 | Use an organizational S/MIME certificate. |
| Unknown or expired CAWG preparation token | 4000 | Call prepare again and complete within C2PA_CAWG_CONTEXT_EXPIRY_SECS. |
| CAWG signature does not verify | 5022 | Sign hash_to_sign_b64 with the private key for the supplied chain using cawg_algorithm. |
| Signing service rate limit reached | 4029 | Retry with backoff. |
| Bindings declare the ABI 1 argument list, C2paSignedResult, or C2paPrepareResult | Missing symbol, undefined behaviour, or misreported errors | Rebuild 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 macOS | Start-up failure | Rewrite the install name as described in 1.1. |
| Missing input or library | Local path or load error | Validate paths and architecture. |
| Modified signed file | assertion.dataHash.mismatch | Treat the asset as changed. |
Unsigned target is its only ingredient and new_creation=true | 4000 | Use new_creation=false for the self-parent/opened flow. |
| Target appears alongside another ingredient with distinct IDs | 4000 | Remove the target from the ingredient list or use the target as its only self-parent. |
Empty binary asset passed to c2pa_sign | 4003 | Provide a non-empty supported asset. Sidecar validation rejects empty buffers with 4000. |
| Claim-generator value rejected by the service | 5020; HTTP 400 invalid_request | Retain the default DigiCert Content Trust Manager claim-generator name. |
| Required library-version header missing | 5020; HTTP 400 invalid_request | Leave C2PA_SEND_DTM_MSL_HEADER at its default true. |
Platform and tool compatibility
| Component | Version or platform | Integration notes |
|---|---|---|
| macOS library | arm64 and x86_64 | Use the .dylib package matching the application architecture. See section 1.1 for C and Go linking. |
| Rust | Rust 1.89.0; libloading 0.8; anyhow 1; serde_json 1 | Load the platform library with libloading and call the C-compatible interface. |
| Python | Python 3.9.6 or later | Use the standard ctypes module. |
| C | Apple clang on arm64 or x86_64 | Include c2pa_msl.h and link the native library. |
| C# | .NET 8 or later | Use P/Invoke and System.Text.Json. The project commands below target .NET 10. |
Node.js | Node.js 26.0.0; Koffi 3.3.6 | Use Koffi to call the C-compatible interface. |
| Go | Go 1.26.7 on darwin/arm64 | Use cgo and the C header. |
| Java | OpenJDK 21; JNA 5.17.0 | Use JNA to call the C-compatible interface. |
| c2patool | 0.28.4 | Use detailed inspection and the trust subcommand to verify generated assets. |
References
- S/MIME BR certificate setup
- C2PA AI disclosure specification
- arXiv taxonomy reference
- C2PA 2.4 actions specification
- IPTC Digital Source Type vocabulary