Ir para o conteúdo principal
Certyneo
Selo avançado · eIDAS art. 36

Selo eletrónico avançado por API, com a sua própria chave

O selo avançado da Certyneo é aposto em dois passos com uma chave que a sua organização gera e conserva (HSM, serviço de gestão de chaves ou ficheiro protegido). Submete um pedido de certificado (CSR), o seu representante legal assina um aditamento ao mandato e cada selo faz-se em duas chamadas: preparação e assinatura.

A chave privada fica consigo

A Certyneo recebe um CSR e, em cada selo, um valor de assinatura. Nunca a chave.

Certificado de um ano, revogável

Emitido em nome da denominação social do registo, publicado numa lista de revogação (CRL).

PAdES-B-T com carimbo temporal

Cada selo incorpora no PDF um token de carimbo temporal RFC 3161.

O que este selo não oferece

  • Sem visto verde nos leitores de PDF: a autoridade da Certyneo não consta nem da lista de confiança da UE nem da da Adobe. O leitor mostra «validade desconhecida» até o verificador adicionar o nosso certificado de raiz.
  • Sem presunção legal de integridade e de origem (eIDAS art. 35.2): está reservada ao selo qualificado. Um selo avançado é admissível como prova, mas cabe a quem o invoca demonstrar a sua fiabilidade.
  • Não abrange as faturas eletrónicas entre empresas: para a via do selo, o artigo 289 VII do código fiscal francês exige um selo qualificado. A utilização invoice_b2b é recusada.
  • A guarda da chave fica a seu cargo: armazenamento, cópia de segurança, renovação e comunicação imediata de qualquer comprometimento.

O selo avançado é ativado organização a organização. Enquanto não estiver ativo para a sua, as rotas deste guia recusam o pedido, sem nunca o rebaixar para um selo simples: 501 SEAL_LEVEL_NOT_AVAILABLE

Antes de começar

  • Uma identidade de selo ativa (registo verificado, mandato assinado pelo representante legal), o direito ao selo (plano Business ou superior, ou opção Selo eletrónico) e um certificado de selo avançado pago na página Faturação antes do envio da chave. O identificador da identidade, a usar na API, é apresentado nas definições do selo eletrónico
  • Uma chave API com a permissão seals:write
  • O seu representante legal, contactável por e-mail e por SMS: é ele quem assina o aditamento que designa a chave.

Registar a chave da sua organização

O registo faz-se uma vez por chave e depois em cada renovação. Liga uma chave concreta à decisão da sua organização.

1.Gerar o par de chaves

Algoritmos aceites: ECDSA P-256 ou P-384, RSA de 2048 bits ou mais. Gere a chave onde ela vai ficar: de preferência num HSM ou num serviço de gestão de chaves; caso contrário, num ficheiro com permissões restritas.

# 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.Pedir um desafio

O desafio é válido durante 15 minutos e está ligado à sua identidade de selo: um CSR antigo, ou feito para outra empresa, não pode ser reutilizado.

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.Criar o pedido de certificado (CSR)

O desafio é colocado no atributo challengePassword do CSR. É um atributo, não uma extensão: com o OpenSSL, define-se na secção req_attributes de um ficheiro de configuração. O sujeito do CSR é ignorado: o certificado contém a denominação social do registo.

# 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

Chave num HSM ou num serviço de gestão de chaves: o mesmo CSR faz-se através da respetiva interface PKCS#11 e a chave privada não sai do 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.Submeter o CSR e obter a assinatura do aditamento

A chave passa ao estado PENDING_MANDATE e é enviado ao seu representante legal um aditamento ao mandato, onde figura a impressão digital da chave. Assim que ele o assina com o código SMS, o certificado de um ano é emitido e a chave passa ao 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}'

Renovação: nova chave, novo CSR, novo aditamento. As duas chaves coexistem durante o período de sobreposição. Um e-mail avisa-o 30 e depois 7 dias antes do fim da validade.

Apor um selo em dois passos

Como a chave fica consigo, a Certyneo não pode selar numa única chamada:

  1. POST /api/v1/seals com level=ADVANCED e keyId: a Certyneo prepara o PDF e devolve os bytes exatos a assinar (signing.signedAttributes). Ainda nada foi selado.
  2. Assina esses bytes com a sua chave, em SHA-256. ECDSA: assinatura DER ou r‖s; RSA: PKCS#1 v1.5.
  3. No prazo de 15 minutos, POST para signatureUrl (/api/v1/seals/…/signature): a Certyneo verifica a assinatura com o certificado da chave, aplica o carimbo temporal, insere o selo e devolve a ligação do PDF.

Na linha 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

Com um HSM, a assinatura faz-se através da respetiva interface PKCS#11; um serviço que assina um hash recebe 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;
}

Uma assinatura recusada (422 SEAL_SIGNATURE_INVALID) mantém a preparação aberta: envie uma assinatura corrigida. Se o carimbo temporal estiver momentaneamente indisponível (503 SEAL_TIMESTAMP_UNAVAILABLE), volte a enviar a mesma assinatura um pouco mais tarde.

Selar em lote

Até 25 documentos por chamada, com a mesma chave. A preparação é tudo ou nada; na assinatura, cada selo é concluído ou falha isoladamente, com o seu próprio 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 teste

Com uma chave API de teste (sk_test_*), todo o percurso funciona sem vincular a sua organização:

  • O certificado é emitido por uma autoridade de TEST distinta, sem ligação à raiz da Certyneo. O seu nome começa por [TEST] e nunca vale como selo de produção.
  • Não é enviado nenhum aditamento: a ativação é simulada, a chave fica ACTIVE de imediato e a resposta indica-o (mandate.simulated = true).
  • Uma chave de teste só sela em teste e uma chave de produção só em produção. A mesma chave pode ser registada em teste e depois em produção, com um novo CSR e um aditamento real.
  • As chaves e os selos de teste são eliminados com os restantes dados de teste, ao fim de 30 dias ou a pedido. Um selo de teste não tem certificado de prova.

Se o modo de teste não estiver ativo para a sua conta, uma chave de teste recebe: 501 SEAL_KEY_SANDBOX_NOT_AVAILABLE

Revogar uma chave

Uma chave revogada consta da lista de revogação a partir da leitura seguinte. A revogação é definitiva. Em caso de dúvida sobre a chave, revogue-a com o motivo keyCompromise e registe uma nova.

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 erro

Cada recusa traz um código estável em details.code, que não muda com o idioma nem com o texto da mensagem. Teste esse código.

CódigoHTTPSignificado e o que fazer
SEAL_LEVEL_NOT_AVAILABLE501O selo avançado não está ativo para a sua organização. Nada foi produzido nem rebaixado para selo simples.
SEAL_KEY_SANDBOX_NOT_AVAILABLE501Registo com uma chave de teste sem o modo de teste ativo. Nenhuma chave foi registada.
SEAL_SANDBOX_NOT_AVAILABLE501Selo com uma chave de teste sem o modo de teste ativo. Nenhum selo foi produzido.
CSR_*422O CSR foi recusado: formato, algoritmo, tamanho da chave, assinatura ou desafio em falta. Corrija o CSR e submeta-o de novo.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_EXPIRED422O desafio tem mais de 15 minutos. Peça um novo e refaça o CSR.
SEAL_KEY_CHALLENGE_INVALID422O desafio não corresponde a esta identidade de selo.
SEAL_KEY_KEY_ALREADY_ENROLLED409Esta chave pública já está registada para esta identidade, neste ambiente.
SEAL_KEY_AMENDMENT_PENDING409Outra chave aguarda a assinatura do aditamento. Aguarde essa assinatura ou revogue essa chave.
SEAL_CERTIFICATE_PAYMENT_REQUIRED402Não há nenhum certificado avançado pago disponível: cada certificado é pago antes da sua emissão, na página Faturação. Nenhuma chave foi registada.
SEAL_KEY_NOT_ACTIVE409A chave não está ativa: aditamento não assinado, chave revogada ou expirada.
SEAL_PURPOSE_NOT_AVAILABLE422O selo avançado não abrange as faturas entre empresas: o artigo 289 VII do código fiscal francês exige um selo qualificado.
SEAL_SIGNATURE_INVALID422A assinatura não é validada pelo certificado da chave. Assine exatamente signedAttributes, em SHA-256, com a chave registada.
SEAL_PREPARATION_EXPIRED409Passaram mais de 15 minutos entre a preparação e a assinatura. Prepare o documento de novo.
SEAL_TIMESTAMP_UNAVAILABLE503O serviço de carimbo temporal não respondeu. Nada foi selado: volte a enviar a mesma assinatura após o prazo indicado em Retry-After.
SEAL_MONTHLY_CEILING_REACHED429Limite de segurança do mês atingido para este certificado: o selo é retomado no dia 1 do mês seguinte. Escreva-nos para o aumentar.

Para saber mais