Vai al contenuto principale
Certyneo
Sigillo avanzato · eIDAS art. 36

Sigillo elettronico avanzato via API, con la tua chiave

Il sigillo avanzato di Certyneo si appone in due fasi con una chiave che la tua organizzazione genera e conserva (HSM, servizio di gestione delle chiavi o file protetto). Invii una richiesta di certificato (CSR), il tuo rappresentante legale firma un addendum al mandato, poi ogni sigillo richiede due chiamate: preparazione e firma.

La chiave privata resta da te

Certyneo riceve una CSR e poi, per ogni sigillo, un valore di firma. Mai la chiave.

Certificato di un anno, revocabile

Emesso a nome della ragione sociale iscritta nel registro, pubblicato in un elenco di revoca (CRL).

PAdES-B-T con marca temporale

Ogni sigillo incorpora nel PDF un token di marca temporale RFC 3161.

Cosa non offre questo sigillo

  • Nessuna spunta verde nei lettori PDF: l'autorità Certyneo non figura né nell'elenco di fiducia dell'UE né in quello di Adobe. Il lettore mostra «validità sconosciuta» finché il verificatore non aggiunge il nostro certificato radice.
  • Nessuna presunzione legale di integrità e di origine (eIDAS art. 35.2): è riservata al sigillo qualificato. Un sigillo avanzato è ammissibile come prova, ma spetta a chi lo invoca dimostrarne l'affidabilità.
  • Non copre le fatture elettroniche tra imprese: per la via del sigillo, l'articolo 289 VII del codice tributario francese richiede un sigillo qualificato. L'uso invoice_b2b viene rifiutato.
  • La custodia della chiave è a tuo carico: conservazione, backup, rinnovo e segnalazione immediata di una compromissione.

Il sigillo avanzato viene attivato organizzazione per organizzazione. Finché non è attivo per la tua, le rotte di questa guida rifiutano la richiesta, senza mai declassarla a sigillo semplice: 501 SEAL_LEVEL_NOT_AVAILABLE

Prima di iniziare

  • Un'identità di sigillo attiva (registro verificato, mandato firmato dal rappresentante legale), il diritto al sigillo (piano Business o superiore, oppure opzione Sigillo elettronico) e un certificato di sigillo avanzato pagato dalla pagina Fatturazione prima del deposito della chiave. L'identificativo dell'identità, da usare nell'API, è indicato nelle impostazioni del sigillo elettronico
  • Una chiave API con il permesso seals:write
  • Il tuo rappresentante legale, raggiungibile via e-mail e SMS: firma l'addendum che designa la chiave.

Registrare la chiave della tua organizzazione

La registrazione avviene una volta per chiave, poi a ogni rinnovo. Collega una chiave precisa alla decisione della tua organizzazione.

1.Generare la coppia di chiavi

Algoritmi accettati: ECDSA P-256 o P-384, RSA da 2048 bit o più. Genera la chiave dove resterà: preferibilmente in un HSM o in un servizio di gestione delle chiavi; altrimenti in un file con permessi ristretti.

# ECDSA P-256 (recommended)
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out seal-key.pem

# or RSA 3072
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out seal-key.pem

# The private key never leaves your infrastructure. Restrict access to it:
chmod 600 seal-key.pem

2.Richiedere una challenge

La challenge è valida 15 minuti ed è legata alla tua identità di sigillo: una CSR vecchia, o creata per un'altra società, non può essere riutilizzata.

curl -s -X POST https://certyneo.com/api/v1/seal-identities/<IDENTITY_ID>/keys/challenge \
  -H "Authorization: Bearer $CERTYNEO_API_KEY"
# → { "challenge": "ck1.1764079200.9f2c…", "attribute": "challengePassword", "expiresAt": "…" }

3.Creare la richiesta di certificato (CSR)

La challenge va inserita nell'attributo challengePassword della CSR. È un attributo, non un'estensione: con OpenSSL, si imposta nella sezione req_attributes di un file di configurazione. Il soggetto della CSR viene ignorato: il certificato riporta la ragione sociale del registro.

# seal-csr.cnf
[req]
prompt             = no
distinguished_name = dn
attributes         = req_attributes

[dn]
# Ignored: the certificate carries the legal name from the company register.
CN = ignored

[req_attributes]
challengePassword = <CHALLENGE>
openssl req -new -key seal-key.pem -config seal-csr.cnf -sha256 -out seal.csr

Chiave in un HSM o in un servizio di gestione delle chiavi: la stessa CSR si crea tramite la sua interfaccia PKCS#11 e la chiave privata non lascia il dispositivo.

# Key generated and kept in an HSM or key management service with a PKCS#11
# interface (OpenSSL 3 + pkcs11-provider). The private key stays in the device.
openssl req -new -provider pkcs11 -provider default \
  -key "pkcs11:token=seal;object=certyneo-seal;type=private" \
  -config seal-csr.cnf -sha256 -out seal.csr

4.Inviare la CSR e far firmare l'addendum

La chiave passa allo stato PENDING_MANDATE e un addendum al mandato, che riporta l'impronta della chiave, viene inviato al tuo rappresentante legale. Appena lo firma con il codice SMS, viene emesso il certificato di un anno e la chiave passa allo stato ACTIVE.

jq -Rs '{csr: .}' seal.csr | curl -s -X POST \
  https://certyneo.com/api/v1/seal-identities/<IDENTITY_ID>/keys \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" \
  -H "Content-Type: application/json" -d @-
# → 201 { "id": "<KEY_ID>", "status": "PENDING_MANDATE",
#         "mandate": { "awaiting": "legal_representative_signature", … } }

# Once the legal representative has signed the amendment, the key is ACTIVE:
curl -s https://certyneo.com/api/v1/seal-identities/<IDENTITY_ID>/keys \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" | jq '.data[] | {id, status, notAfter}'

Rinnovo: nuova chiave, nuova CSR, nuovo addendum. Le due chiavi coesistono durante il periodo di sovrapposizione. Un'e-mail ti avvisa 30 e poi 7 giorni prima della scadenza.

Apporre un sigillo in due fasi

Poiché la chiave resta da te, Certyneo non può apporre il sigillo con una sola chiamata:

  1. POST /api/v1/seals con level=ADVANCED e keyId: Certyneo prepara il PDF e restituisce i byte esatti da firmare (signing.signedAttributes). Non è ancora stato sigillato nulla.
  2. Firmi questi byte con la tua chiave, in SHA-256. ECDSA: firma DER o r‖s; RSA: PKCS#1 v1.5.
  3. Entro 15 minuti, POST su signatureUrl (/api/v1/seals/…/signature): Certyneo verifica la firma con il certificato della chiave, appone la marca temporale, inserisce il sigillo e restituisce il link del PDF.

Da riga di comando

# Step 1 — prepare: Certyneo returns the exact bytes to sign.
curl -s -X POST https://certyneo.com/api/v1/seals \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" \
  -F file=@contract.pdf -F level=ADVANCED -F purpose=internal_document \
  -F keyId=<KEY_ID> > prepared.json
SEAL_ID=$(jq -r .id prepared.json)
jq -r .signing.signedAttributes prepared.json | openssl base64 -d -A > signed-attributes.der

# Sign them with YOUR key (SHA-256). ECDSA output is DER, RSA is PKCS#1 v1.5.
openssl dgst -sha256 -sign seal-key.pem -out signature.der signed-attributes.der

# Step 2 — send the signature: Certyneo verifies it, timestamps and embeds the seal.
SIG=$(openssl base64 -A -in signature.der)
curl -s -X POST https://certyneo.com/api/v1/seals/$SEAL_ID/signature \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" \
  -H "Content-Type: application/json" -d "{\"signature\":\"$SIG\"}" | jq -r .downloadUrl

Con un HSM, la firma avviene tramite la sua interfaccia PKCS#11; un servizio che firma un hash riceve signing.signedAttributesSha256.

# Same signature from a PKCS#11 device:
openssl pkeyutl -sign -provider pkcs11 -provider default \
  -inkey "pkcs11:token=seal;object=certyneo-seal;type=private" \
  -digest sha256 -rawin -in signed-attributes.der -out signature.der

# A key management service that signs a pre-computed digest instead takes
# signing.signedAttributesSha256 (hex) with ECDSA-SHA-256 or RSA PKCS#1 v1.5 SHA-256.

Node.js

// seal.mjs — node seal.mjs contract.pdf
// Env: CERTYNEO_API_KEY, SEAL_KEY_ID, SEAL_PRIVATE_KEY (PEM file path).
import { readFile, writeFile } from "node:fs/promises";
import { createPrivateKey, sign } from "node:crypto";

const base = process.env.CERTYNEO_API_URL ?? "https://certyneo.com";
const auth = { Authorization: `Bearer ${process.env.CERTYNEO_API_KEY}` };
const input = process.argv[2] ?? "contract.pdf";

async function call(path, init) {
  const res = await fetch(base + path, { ...init, headers: { ...auth, ...init.headers } });
  const body = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${body.details?.code ?? body.code}: ${body.error}`);
  return body;
}

// Step 1 — prepare. Nothing is sealed yet.
const form = new FormData();
form.append("file", new Blob([await readFile(input)], { type: "application/pdf" }), "contract.pdf");
form.append("level", "ADVANCED");
form.append("purpose", "internal_document");
form.append("keyId", process.env.SEAL_KEY_ID);
const prepared = await call("/api/v1/seals", { method: "POST", body: form });

// Sign the exact signedAttributes bytes with SHA-256 and YOUR key.
// ECDSA keys give a DER signature, RSA keys PKCS#1 v1.5 — both accepted.
// With an HSM or a key management service, sign here through its SDK instead.
const key = createPrivateKey(await readFile(process.env.SEAL_PRIVATE_KEY, "utf8"));
const signedAttributes = Buffer.from(prepared.signing.signedAttributes, "base64");
const signature = sign("sha256", signedAttributes, key);

// Step 2 — send the signature before prepared.signing.expiresAt (15 minutes).
// 503 SEAL_TIMESTAMP_UNAVAILABLE: send the SAME signature again a little later.
const sealed = await call(`/api/v1/seals/${prepared.id}/signature`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ signature: signature.toString("base64") }),
});

const pdf = Buffer.from(await (await fetch(sealed.downloadUrl)).arrayBuffer());
await writeFile("sealed.pdf", pdf);
console.log(sealed.id, sealed.status, sealed.sealedSha256);

Java

// Seal.java — java Seal.java contract.pdf   (JDK 17+)
// Env: CERTYNEO_API_KEY, SEAL_KEY_ID, SEAL_PRIVATE_KEY (PKCS#8 PEM file path).
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import java.util.regex.*;

public class Seal {
  static final String BASE = Optional.ofNullable(System.getenv("CERTYNEO_API_URL")).orElse("https://certyneo.com");
  static final HttpClient HTTP = HttpClient.newHttpClient();

  public static void main(String[] args) throws Exception {
    String auth = "Bearer " + System.getenv("CERTYNEO_API_KEY");
    byte[] pdf = Files.readAllBytes(Path.of(args.length > 0 ? args[0] : "contract.pdf"));

    // Step 1 — prepare (multipart/form-data).
    String boundary = "----certyneo" + UUID.randomUUID();
    var body = new java.io.ByteArrayOutputStream();
    for (String[] f : new String[][] {{"level", "ADVANCED"}, {"purpose", "internal_document"}, {"keyId", System.getenv("SEAL_KEY_ID")}}) {
      body.writeBytes(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + f[0] + "\"\r\n\r\n" + f[1] + "\r\n").getBytes(StandardCharsets.UTF_8));
    }
    body.writeBytes(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"contract.pdf\"\r\nContent-Type: application/pdf\r\n\r\n").getBytes(StandardCharsets.UTF_8));
    body.writeBytes(pdf);
    body.writeBytes(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
    String prepared = send(HttpRequest.newBuilder(URI.create(BASE + "/api/v1/seals"))
        .header("Authorization", auth).header("Content-Type", "multipart/form-data; boundary=" + boundary)
        .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray())).build(), 202);

    // Sign the exact signedAttributes bytes with SHA-256 and YOUR key.
    byte[] signedAttributes = Base64.getDecoder().decode(field(prepared, "signedAttributes"));
    PrivateKey key = loadKey(Files.readString(Path.of(System.getenv("SEAL_PRIVATE_KEY"))));
    Signature signer = Signature.getInstance(key.getAlgorithm().equals("EC") ? "SHA256withECDSA" : "SHA256withRSA");
    signer.initSign(key);
    signer.update(signedAttributes);
    String signature = Base64.getEncoder().encodeToString(signer.sign()); // ECDSA: DER

    // Step 2 — send the signature within 15 minutes.
    String sealed = send(HttpRequest.newBuilder(URI.create(BASE + "/api/v1/seals/" + field(prepared, "id") + "/signature"))
        .header("Authorization", auth).header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("{\"signature\":\"" + signature + "\"}")).build(), 201);

    byte[] out = HTTP.send(HttpRequest.newBuilder(URI.create(field(sealed, "downloadUrl"))).build(),
        HttpResponse.BodyHandlers.ofByteArray()).body();
    Files.write(Path.of("sealed.pdf"), out);
    System.out.println(field(sealed, "id") + " " + field(sealed, "status"));
  }

  static String send(HttpRequest req, int expected) throws Exception {
    HttpResponse<String> res = HTTP.send(req, HttpResponse.BodyHandlers.ofString());
    if (res.statusCode() != expected) throw new IllegalStateException(res.statusCode() + " " + res.body());
    return res.body();
  }

  static PrivateKey loadKey(String pem) throws Exception {
    byte[] der = Base64.getMimeDecoder().decode(pem.replaceAll("-----[A-Z ]+-----", ""));
    for (String alg : new String[] {"EC", "RSA"}) {
      try { return KeyFactory.getInstance(alg).generatePrivate(new PKCS8EncodedKeySpec(der)); }
      catch (java.security.spec.InvalidKeySpecException e) { /* try the next algorithm */ }
    }
    throw new IllegalArgumentException("Expected an EC or RSA key in PKCS#8 PEM (openssl genpkey output)");
  }

  // Minimal reader for the string fields used here; use your JSON library in production.
  static String field(String json, String name) {
    Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json);
    if (!m.find()) throw new IllegalStateException("missing " + name + " in " + json);
    return m.group(1);
  }
}

.NET (C#)

// Program.cs — dotnet run -- contract.pdf   (.NET 6+)
// Env: CERTYNEO_API_KEY, SEAL_KEY_ID, SEAL_PRIVATE_KEY (PEM file path).
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text.Json;

var baseUrl = Environment.GetEnvironmentVariable("CERTYNEO_API_URL") ?? "https://certyneo.com";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CERTYNEO_API_KEY"));

// Step 1 — prepare. Nothing is sealed yet.
using var form = new MultipartFormDataContent();
var file = new ByteArrayContent(await File.ReadAllBytesAsync(args.Length > 0 ? args[0] : "contract.pdf"));
file.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
form.Add(file, "file", "contract.pdf");
form.Add(new StringContent("ADVANCED"), "level");
form.Add(new StringContent("internal_document"), "purpose");
form.Add(new StringContent(Environment.GetEnvironmentVariable("SEAL_KEY_ID")!), "keyId");
var prepared = await Send(await http.PostAsync($"{baseUrl}/api/v1/seals", form));

// Sign the exact signedAttributes bytes with SHA-256 and YOUR key.
var signedAttributes = Convert.FromBase64String(
    prepared.GetProperty("signing").GetProperty("signedAttributes").GetString()!);
var pem = await File.ReadAllTextAsync(Environment.GetEnvironmentVariable("SEAL_PRIVATE_KEY")!);
byte[] signature;
if (prepared.GetProperty("signing").GetProperty("signatureAlgorithm").GetString() == "ECDSA_SHA256")
{
    using var ec = ECDsa.Create();
    ec.ImportFromPem(pem);
    // .NET signs ECDSA in r||s (P1363) by default; DER and P1363 are both accepted.
    signature = ec.SignData(signedAttributes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
}
else
{
    using var rsa = RSA.Create();
    rsa.ImportFromPem(pem);
    signature = rsa.SignData(signedAttributes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

// Step 2 — send the signature within 15 minutes.
var id = prepared.GetProperty("id").GetString();
var sealed = await Send(await http.PostAsJsonAsync(
    $"{baseUrl}/api/v1/seals/{id}/signature", new { signature = Convert.ToBase64String(signature) }));

var pdf = await new HttpClient().GetByteArrayAsync(sealed.GetProperty("downloadUrl").GetString());
await File.WriteAllBytesAsync("sealed.pdf", pdf);
Console.WriteLine($"{sealed.GetProperty("id")} {sealed.GetProperty("status")}");

static async Task<JsonElement> Send(HttpResponseMessage res)
{
    var json = await res.Content.ReadFromJsonAsync<JsonElement>();
    if (!res.IsSuccessStatusCode) throw new Exception($"{(int)res.StatusCode} {json}");
    return json;
}

Una firma rifiutata (422 SEAL_SIGNATURE_INVALID) lascia aperta la preparazione: invia una firma corretta. Se la marca temporale è momentaneamente non disponibile (503 SEAL_TIMESTAMP_UNAVAILABLE), invia di nuovo la stessa firma poco dopo.

Sigillare in blocco

Fino a 25 documenti per chiamata, con la stessa chiave. La preparazione è tutto o niente; alla firma, ogni sigillo riesce o fallisce da solo, con il proprio codice.

# Prepare up to 25 documents with the same key (all or nothing).
curl -s -X POST https://certyneo.com/api/v1/seals/batch \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" \
  -F file=@a.pdf -F file=@b.pdf -F file=@c.pdf \
  -F purpose=internal_document -F keyId=<KEY_ID>
# → 202 { "seals": [ { "id", "signing": { "signedAttributes", … } }, … ] }

# Send every signature in one call; each seal succeeds or fails on its own.
curl -s -X POST https://certyneo.com/api/v1/seals/batch/signatures \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" -H "Content-Type: application/json" \
  -d '{ "signatures": [ { "sealId": "…", "signature": "<base64>" }, … ] }'
# → 200 { "sealed": 2, "refused": 1,
#         "results": [ { "sealId", "status": 201, "seal": { … } },
#                      { "sealId", "status": 422, "error": { "code": "SEAL_SIGNATURE_INVALID", … } } ] }

Modalità test

Con una chiave API di test (sk_test_*), l'intero percorso funziona senza impegnare la tua organizzazione:

  • Il certificato è emesso da un'autorità di TEST distinta, senza legame con la radice Certyneo. Il suo nome inizia con [TEST] e non vale mai come sigillo di produzione.
  • Nessun addendum viene inviato: l'attivazione è simulata, la chiave è subito ACTIVE e la risposta lo indica (mandate.simulated = true).
  • Una chiave di test sigilla solo in test, una chiave di produzione solo in produzione. La stessa chiave può essere registrata in test, poi in produzione con una nuova CSR e un vero addendum.
  • Chiavi e sigilli di test vengono eliminati con il resto dei dati di test, dopo 30 giorni o su richiesta. Un sigillo di test non ha un certificato di prova.

Se la modalità test non è attiva per il tuo account, una chiave di test riceve: 501 SEAL_KEY_SANDBOX_NOT_AVAILABLE

Revocare una chiave

Una chiave revocata compare nell'elenco di revoca dalla lettura successiva. La revoca è definitiva. In caso di dubbio sulla chiave, revocala con il motivo keyCompromise, poi registrane una nuova.

curl -s -X POST https://certyneo.com/api/v1/seal-identities/<IDENTITY_ID>/keys/<KEY_ID>/revoke \
  -H "Authorization: Bearer $CERTYNEO_API_KEY" -H "Content-Type: application/json" \
  -d '{ "reason": "keyCompromise" }'

Codici di errore

Ogni rifiuto riporta un codice stabile in details.code, che non cambia né con la lingua né con il testo del messaggio. Verifica questo codice.

CodiceHTTPSignificato e cosa fare
SEAL_LEVEL_NOT_AVAILABLE501Il sigillo avanzato non è attivo per la tua organizzazione. Non è stato prodotto nulla, né declassato a sigillo semplice.
SEAL_KEY_SANDBOX_NOT_AVAILABLE501Registrazione con una chiave di test mentre la modalità test non è attiva. Nessuna chiave è stata registrata.
SEAL_SANDBOX_NOT_AVAILABLE501Sigillo con una chiave di test mentre la modalità test non è attiva. Nessun sigillo è stato prodotto.
CSR_*422La CSR è rifiutata: formato, algoritmo, dimensione della chiave, firma o challenge mancante. Correggi la CSR e inviala di nuovo.CSR_MALFORMED · CSR_UNSUPPORTED_SIGNATURE_ALGORITHM · CSR_KEY_UNREADABLE · CSR_KEY_ALGORITHM · CSR_KEY_TOO_SMALL · CSR_SIGNATURE_INVALID · CSR_CHALLENGE_MISSING
SEAL_KEY_CHALLENGE_EXPIRED422La challenge ha più di 15 minuti. Richiedine una nuova e rifai la CSR.
SEAL_KEY_CHALLENGE_INVALID422La challenge non corrisponde a questa identità di sigillo.
SEAL_KEY_KEY_ALREADY_ENROLLED409Questa chiave pubblica è già registrata per questa identità, in questo ambiente.
SEAL_KEY_AMENDMENT_PENDING409Un'altra chiave è in attesa della firma dell'addendum. Attendi la firma, oppure revoca quella chiave.
SEAL_CERTIFICATE_PAYMENT_REQUIRED402Nessun certificato avanzato pagato è disponibile: ogni certificato si paga prima della sua emissione, dalla pagina Fatturazione. Nessuna chiave è stata registrata.
SEAL_KEY_NOT_ACTIVE409La chiave non è attiva: addendum non firmato, chiave revocata o scaduta.
SEAL_PURPOSE_NOT_AVAILABLE422Il sigillo avanzato non copre le fatture tra imprese: l'articolo 289 VII del codice tributario francese richiede un sigillo qualificato.
SEAL_SIGNATURE_INVALID422La firma non risulta valida con il certificato della chiave. Firma esattamente signedAttributes, in SHA-256, con la chiave registrata.
SEAL_PREPARATION_EXPIRED409Più di 15 minuti tra la preparazione e la firma. Prepara di nuovo il documento.
SEAL_TIMESTAMP_UNAVAILABLE503Il servizio di marca temporale non ha risposto. Non è stato sigillato nulla: invia di nuovo la stessa firma dopo il tempo indicato da Retry-After.
SEAL_MONTHLY_CEILING_REACHED429Soglia di sicurezza del mese raggiunta per questo certificato: il sigillo riprende il 1° del mese successivo. Ci scriva per alzarla.

Per approfondire