Selo eletrônico avançado via API, com a sua própria chave
O selo avançado da Certyneo é aposto em duas etapas com uma chave que a sua organização gera e mantém (HSM, serviço de gerenciamento de chaves ou arquivo protegido). Você envia uma solicitação de certificado (CSR), o seu representante legal assina um aditivo ao mandato e cada selo é feito em duas chamadas: preparação e assinatura.
A chave privada fica com você
A Certyneo recebe uma CSR e, a cada selo, um valor de assinatura. Nunca a chave.
Certificado de um ano, revogável
Emitido em nome da razão social do registro, publicado em uma lista de revogação (CRL).
PAdES-B-T com carimbo de tempo
Cada selo incorpora ao PDF um token de carimbo de tempo RFC 3161.
O que este selo não oferece
- Sem marca de seleção verde nos leitores de PDF: a autoridade da Certyneo não consta da lista de confiança da UE nem da lista da Adobe. O leitor exibe “validade desconhecida” até que o verificador adicione o nosso certificado raiz.
- Sem presunção legal de integridade e de origem (eIDAS art. 35.2): ela é reservada ao selo qualificado. Um selo avançado é admissível como prova, mas cabe a quem o invoca demonstrar a sua confiabilidade.
- Não cobre as notas fiscais eletrônicas entre empresas: para a via do selo, o artigo 289 VII do código tributário francês exige um selo qualificado. O uso invoice_b2b é recusado.
- A guarda da chave é de sua responsabilidade: armazenamento, backup, renovação e comunicação imediata de qualquer comprometimento.
O selo avançado é liberado organização por organização. Enquanto não estiver liberado para a sua, as rotas deste guia recusam a solicitação, sem nunca rebaixá-la para um selo simples: 501 SEAL_LEVEL_NOT_AVAILABLE
Antes de começar
- Uma identidade de selo ativa (registro 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 Faturamento antes do envio da chave. O identificador da identidade, usado na API, é exibido nas configurações do selo eletrônico
- Uma chave API com a permissão
seals:write - O seu representante legal, acessível por e-mail e por SMS: é ele quem assina o aditivo que designa a chave.
Registrar a chave da sua organização
O registro é feito uma vez por chave e depois a cada renovação. Ele vincula uma chave específica à decisão da sua organização.
1.Gerar o par de chaves
Algoritmos aceitos: ECDSA P-256 ou P-384, RSA de 2048 bits ou mais. Gere a chave onde ela vai ficar: de preferência em um HSM ou em um serviço de gerenciamento de chaves; caso contrário, em um arquivo 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.pem2.Solicitar um desafio
O desafio é válido por 15 minutos e vinculado à sua identidade de selo: uma CSR antiga, ou feita para outra empresa, não pode ser reutilizada.
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 a solicitação de certificado (CSR)
O desafio vai no atributo challengePassword da CSR. É um atributo, não uma extensão: com o OpenSSL, ele é definido na seção req_attributes de um arquivo de configuração. O assunto da CSR é ignorado: o certificado traz a razão social do 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.csrChave em um HSM ou em um serviço de gerenciamento de chaves: a mesma CSR é feita pela interface PKCS#11 dele, 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.csr4.Enviar a CSR e obter a assinatura do aditivo
A chave passa para o status PENDING_MANDATE e um aditivo ao mandato, no qual consta a impressão digital da chave, é enviado ao seu representante legal. Assim que ele o assina com o código SMS, o certificado de um ano é emitido e a chave passa para o status 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, nova CSR, novo aditivo. As duas chaves coexistem durante o período de sobreposição. Um e-mail avisa você 30 e depois 7 dias antes do vencimento.
Aplicar um selo em duas etapas
Como a chave fica com você, a Certyneo não consegue selar em uma única chamada:
- POST /api/v1/seals com level=ADVANCED e keyId: a Certyneo prepara o PDF e retorna os bytes exatos a serem assinados (signing.signedAttributes). Nada foi selado ainda.
- Você assina esses bytes com a sua chave, em SHA-256. ECDSA: assinatura DER ou r‖s; RSA: PKCS#1 v1.5.
- Em até 15 minutos, POST para signatureUrl (/api/v1/seals/…/signature): a Certyneo verifica a assinatura com o certificado da chave, aplica o carimbo de tempo, insere o selo e retorna o link do PDF.
Pela linha de 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 .downloadUrlCom um HSM, a assinatura é feita pela interface PKCS#11 dele; 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 de tempo estiver indisponível no momento (503 SEAL_TIMESTAMP_UNAVAILABLE), envie a mesma assinatura novamente 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 separadamente, 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 fluxo funciona sem comprometer a sua organização:
- O certificado é emitido por uma autoridade de TEST separada, sem vínculo com a raiz da Certyneo. O nome dele começa com [TEST] e ele nunca vale como selo de produção.
- Nenhum aditivo é enviado: a ativação é simulada, a chave fica ACTIVE na hora e a resposta indica isso (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 registrada em teste e depois em produção, com uma nova CSR e um aditivo real.
- Chaves e selos de teste são excluídos junto com os demais dados de teste, após 30 dias ou mediante solicitação. Um selo de teste não tem certificado de comprovação.
Se o modo de teste não estiver liberado para a sua conta, uma chave de teste recebe: 501 SEAL_KEY_SANDBOX_NOT_AVAILABLE
Revogar uma chave
Uma chave revogada aparece na lista de revogação a partir da leitura seguinte. A revogação é definitiva. Se houver qualquer dúvida sobre a chave, revogue-a com o motivo keyCompromise e registre 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ódigo | HTTP | Significado e o que fazer |
|---|---|---|
SEAL_LEVEL_NOT_AVAILABLE | 501 | O selo avançado não está liberado para a sua organização. Nada foi produzido nem rebaixado para selo simples. |
SEAL_KEY_SANDBOX_NOT_AVAILABLE | 501 | Registro com uma chave de teste sem o modo de teste liberado. Nenhuma chave foi registrada. |
SEAL_SANDBOX_NOT_AVAILABLE | 501 | Selo com uma chave de teste sem o modo de teste liberado. Nenhum selo foi produzido. |
CSR_* | 422 | A CSR foi recusada: formato, algoritmo, tamanho da chave, assinatura ou desafio ausente. Corrija a CSR e envie-a novamente.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_EXPIRED | 422 | O desafio tem mais de 15 minutos. Solicite um novo e refaça a CSR. |
SEAL_KEY_CHALLENGE_INVALID | 422 | O desafio não corresponde a esta identidade de selo. |
SEAL_KEY_KEY_ALREADY_ENROLLED | 409 | Esta chave pública já está registrada para esta identidade, neste ambiente. |
SEAL_KEY_AMENDMENT_PENDING | 409 | Outra chave aguarda a assinatura do aditivo. Aguarde essa assinatura ou revogue essa chave. |
SEAL_CERTIFICATE_PAYMENT_REQUIRED | 402 | Nenhum certificado avançado pago está disponível: cada certificado é pago antes da emissão, na página Faturamento. Nenhuma chave foi registrada. |
SEAL_KEY_NOT_ACTIVE | 409 | A chave não está ativa: aditivo não assinado, chave revogada ou expirada. |
SEAL_PURPOSE_NOT_AVAILABLE | 422 | O selo avançado não cobre as notas fiscais entre empresas: o artigo 289 VII do código tributário francês exige um selo qualificado. |
SEAL_SIGNATURE_INVALID | 422 | A assinatura não é validada pelo certificado da chave. Assine exatamente signedAttributes, em SHA-256, com a chave registrada. |
SEAL_PREPARATION_EXPIRED | 409 | Mais de 15 minutos entre a preparação e a assinatura. Prepare o documento novamente. |
SEAL_TIMESTAMP_UNAVAILABLE | 503 | O serviço de carimbo de tempo não respondeu. Nada foi selado: envie a mesma assinatura novamente após o prazo indicado em Retry-After. |
SEAL_MONTHLY_CEILING_REACHED | 429 | Limite de segurança do mês atingido para este certificado: o selo volta a funcionar no dia 1º do mês seguinte. Escreva para nós para aumentá-lo. |