Ir al contenido principal
Certyneo
Sello avanzado · eIDAS art. 36

Sello electrónico avanzado por API, con su propia clave

El sello avanzado de Certyneo se estampa en dos fases con una clave que su organización genera y conserva (HSM, servicio de gestión de claves o archivo protegido). Usted envía una solicitud de certificado (CSR), su representante legal firma una adenda al mandato y cada sello se hace en dos llamadas: preparación y firma.

La clave privada se queda con usted

Certyneo recibe una CSR y, en cada sello, un valor de firma. Nunca la clave.

Certificado de un año, revocable

Emitido a nombre de la razón social del registro, publicado en una lista de revocación (CRL).

PAdES-B-T con marca de tiempo

Cada sello incorpora en el PDF un token de marca de tiempo RFC 3161.

Lo que este sello no ofrece

  • Sin marca verde en los lectores de PDF: la autoridad de Certyneo no figura ni en la lista de confianza de la UE ni en la de Adobe. El lector muestra «validez desconocida» hasta que el verificador añade nuestro certificado raíz.
  • Sin presunción legal de integridad y origen (eIDAS art. 35.2): está reservada al sello cualificado. Un sello avanzado es admisible como prueba, pero quien lo invoca debe demostrar su fiabilidad.
  • No cubre las facturas electrónicas entre empresas: para la vía del sello, el artículo 289 VII del Código General de Impuestos francés exige un sello cualificado. El uso invoice_b2b se rechaza.
  • La custodia de la clave corre a su cargo: almacenamiento, copia de seguridad, renovación y notificación inmediata de cualquier compromiso.

El sello avanzado se habilita organización por organización. Mientras no esté habilitado para la suya, las rutas de esta guía rechazan la solicitud, sin rebajarla nunca a un sello simple: 501 SEAL_LEVEL_NOT_AVAILABLE

Antes de empezar

  • Una identidad de sello activa (registro verificado, mandato firmado por el representante legal), el derecho al sello (plan Business o superior, u opción Sello electrónico) y un certificado de sello avanzado pagado desde la página Facturación antes de registrar la clave. El identificador de la identidad, que se usa en la API, aparece en la configuración del sello electrónico
  • Una clave API con el permiso seals:write
  • Su representante legal, localizable por correo electrónico y por SMS: firma la adenda que designa la clave.

Registrar la clave de su organización

El registro se hace una vez por clave y luego en cada renovación. Vincula una clave concreta a la decisión de su organización.

1.Generar el par de claves

Algoritmos aceptados: ECDSA P-256 o P-384, RSA de 2048 bits o más. Genere la clave donde vaya a permanecer: preferiblemente en un HSM o en un servicio de gestión de claves; si no, en un archivo con permisos restringidos.

# 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.Solicitar un desafío

El desafío es válido durante 15 minutos y está vinculado a su identidad de sello: una CSR antigua, o hecha para otra empresa, no puede reutilizarse.

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.Crear la solicitud de certificado (CSR)

El desafío va en el atributo challengePassword de la CSR. Es un atributo, no una extensión: con OpenSSL, se indica en la sección req_attributes de un archivo de configuración. El sujeto de la CSR se ignora: el certificado lleva la razón social 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

Clave en un HSM o en un servicio de gestión de claves: la misma CSR se hace a través de su interfaz PKCS#11 y la clave privada no sale del 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.Enviar la CSR y hacer firmar la adenda

La clave pasa al estado PENDING_MANDATE y se envía a su representante legal una adenda al mandato que muestra la huella de la clave. En cuanto la firma con su código SMS, se emite el certificado de un año y la clave pasa al estado 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}'

Renovación: nueva clave, nueva CSR, nueva adenda. Las dos claves coexisten durante el periodo de solapamiento. Un correo electrónico le avisa 30 y luego 7 días antes del vencimiento.

Estampar un sello en dos fases

Como la clave se queda con usted, Certyneo no puede sellar en una sola llamada:

  1. POST /api/v1/seals con level=ADVANCED y keyId: Certyneo prepara el PDF y devuelve los bytes exactos que deben firmarse (signing.signedAttributes). Todavía no se ha sellado nada.
  2. Usted firma esos bytes con su clave, en SHA-256. ECDSA: firma DER o r‖s; RSA: PKCS#1 v1.5.
  3. En un plazo de 15 minutos, POST a signatureUrl (/api/v1/seals/…/signature): Certyneo verifica la firma con el certificado de la clave, añade la marca de tiempo, inserta el sello y devuelve el enlace del PDF.

Desde la línea de comandos

# 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 se hace a través de su interfaz PKCS#11; un servicio que firma un hash recibe 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 rechazada (422 SEAL_SIGNATURE_INVALID) deja la preparación abierta: envíe una firma corregida. Si la marca de tiempo no está disponible momentáneamente (503 SEAL_TIMESTAMP_UNAVAILABLE), vuelva a enviar la misma firma un poco más tarde.

Sellar por lotes

Hasta 25 documentos por llamada, con la misma clave. La preparación es de todo o nada; en la firma, cada sello se completa o falla por separado, con su propio código.

# 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", … } } ] }

Modo de prueba

Con una clave API de prueba (sk_test_*), todo el proceso funciona sin comprometer a su organización:

  • El certificado lo emite una autoridad de TEST distinta, sin relación con la raíz de Certyneo. Su nombre empieza por [TEST] y nunca equivale a un sello de producción.
  • No se envía ninguna adenda: la activación es simulada, la clave queda ACTIVE de inmediato y la respuesta lo indica (mandate.simulated = true).
  • Una clave de prueba solo sella en prueba y una clave de producción solo en producción. Una misma clave puede registrarse en prueba y después en producción con una nueva CSR y una adenda real.
  • Las claves y los sellos de prueba se eliminan con el resto de los datos de prueba, a los 30 días o cuando lo solicite. Un sello de prueba no tiene certificado de evidencias.

Si el modo de prueba no está habilitado para su cuenta, una clave de prueba recibe: 501 SEAL_KEY_SANDBOX_NOT_AVAILABLE

Revocar una clave

Una clave revocada figura en la lista de revocación desde la siguiente lectura. La revocación es definitiva. Ante cualquier duda sobre la clave, revóquela con el motivo keyCompromise y registre una nueva.

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" }'

Códigos de error

Cada rechazo lleva un código estable en details.code, que no cambia ni con el idioma ni con el texto del mensaje. Compruebe ese código.

CódigoHTTPSignificado y qué hacer
SEAL_LEVEL_NOT_AVAILABLE501El sello avanzado no está habilitado para su organización. No se ha producido nada ni se ha rebajado a sello simple.
SEAL_KEY_SANDBOX_NOT_AVAILABLE501Registro con una clave de prueba sin que el modo de prueba esté habilitado. No se ha registrado ninguna clave.
SEAL_SANDBOX_NOT_AVAILABLE501Sello con una clave de prueba sin que el modo de prueba esté habilitado. No se ha producido ningún sello.
CSR_*422La CSR se rechaza: formato, algoritmo, tamaño de clave, firma o desafío ausente. Corrija la CSR y envíela de nuevo.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_EXPIRED422El desafío tiene más de 15 minutos. Solicite uno nuevo y rehaga la CSR.
SEAL_KEY_CHALLENGE_INVALID422El desafío no corresponde a esta identidad de sello.
SEAL_KEY_KEY_ALREADY_ENROLLED409Esta clave pública ya está registrada para esta identidad, en este entorno.
SEAL_KEY_AMENDMENT_PENDING409Otra clave está pendiente de la firma de su adenda. Espere a que se firme o revoque esa clave.
SEAL_CERTIFICATE_PAYMENT_REQUIRED402No hay ningún certificado avanzado pagado disponible: cada certificado se paga antes de su emisión, desde la página Facturación. No se ha registrado ninguna clave.
SEAL_KEY_NOT_ACTIVE409La clave no está activa: adenda sin firmar, clave revocada o caducada.
SEAL_PURPOSE_NOT_AVAILABLE422El sello avanzado no cubre las facturas entre empresas: el artículo 289 VII del Código General de Impuestos francés exige un sello cualificado.
SEAL_SIGNATURE_INVALID422La firma no se verifica con el certificado de la clave. Firme exactamente signedAttributes, en SHA-256, con la clave registrada.
SEAL_PREPARATION_EXPIRED409Han pasado más de 15 minutos entre la preparación y la firma. Prepare de nuevo el documento.
SEAL_TIMESTAMP_UNAVAILABLE503El servicio de marca de tiempo no ha respondido. No se ha sellado nada: vuelva a enviar la misma firma tras el plazo indicado en Retry-After.
SEAL_MONTHLY_CEILING_REACHED429Límite de seguridad del mes alcanzado para este certificado: el sello se reanuda el día 1 del mes siguiente. Escríbanos para ampliarlo.

Para saber más