mTLS Certificate

How the mTLS client certificate works, why it protects your integration, how to request it and how to use it in your application.

What is mTLS

Every API request already travels over HTTPS (TLS) and only comes from the IP addresses registered for your company. In plain TLS, only the server shows a certificate: your application checks that it is talking to the real API, while the API recognizes your application by its IP address and credentials.

mTLS (Mutual TLS) makes the check go both ways. During the connection, your application also presents a client certificate, and the API only accepts the connection if that certificate was issued by us for your company.

BeforeWith mTLS
Who proves its identity in the connectionOnly the APIThe API and your application
What the API checksAllowed IP address, access token and HMACAllowed IP address, client certificate, access token and HMAC
What identifies your applicationIP address and credentialsIP address, credentials and a certificate with a private key that only you hold

mTLS is a new layer. It does not replace anything you already do: the IP allowlist, the Bearer token and the HMAC signature remain required on every request.

How it works

Sequence diagram of the mTLS handshake: the application starts the connection, the API sends its certificate and asks for the client certificate, the application sends its certificate signed with its private key, the API validates it and only then the encrypted session carries the request with the Bearer token and HMAC. Without a valid certificate the connection is rejected before reaching the API.
  1. Your application opens an HTTPS connection to the API.
  2. The API sends its server certificate, as it already does today.
  3. The API asks your application for its client certificate.
  4. Your application sends the certificate and a signature made with the private key stored in the .p12 file. The private key never leaves your server.
  5. The API checks that the certificate was issued by our certificate authority, is within its validity period, was not revoked and that the signature matches.
  6. The encrypted session is open, with both sides authenticated.
  7. Your application sends the API request as usual, with the Authorization and hmac headers.
  8. The API responds.

All of this happens inside your HTTP client library. In your code, the only change is to load the certificate once and attach it to the HTTP client, as shown in the examples below.

Why mTLS protects everyone

  • Only authorized clients reach the API. A leaked access token, client_secret or hmac_key is not enough: without the certificate issued for your company, the connection is refused.
  • Protection against impersonation and interception. Both sides authenticate each other, which blocks man-in-the-middle attacks and connections from fake servers or fake clients.
  • Encrypted data end to end. Everything exchanged travels encrypted, keeping the confidentiality and integrity of your transactions.
  • Traceability. Every connection is tied to an identified certificate, which makes auditing and incident response faster.
  • Regulatory compliance. Mutual authentication follows the security practices expected in the financial and payments system, such as the Central Bank of Brazil guidelines, PCI-DSS and LGPD.

How to request the certificate

Send an e-mail to [email protected] with the subject "Solicitação de certificado mTLS para integração com a API", informing:

  • the company CNPJ;
  • the accounts that use the integration;
  • the institution the certificate must be issued for.

What you receive

ItemDescription
Certificate fileA .p12 file (PKCS#12) with your client certificate and its private key.
PasswordThe password that opens the .p12 file.
Validity365 days. Request a new certificate before it expires (see Renewal).
ScopeOne certificate per company, used for all of its accounts. It only works in the environment it was issued for.
🔒

Treat the .p12 file and its password like a password. Anyone who has both can open connections in the name of your company.

Step 1: Prepare the certificate

Some languages read the .p12 file directly (Java, C#, cURL). Others work better with two PEM files: the certificate (client.crt) and the private key (client.key). Convert once with OpenSSL:

# Certificate (public part)
openssl pkcs12 -legacy -in client.p12 -clcerts -nokeys -out client.crt

# Private key (keep this file protected)
openssl pkcs12 -legacy -in client.p12 -nocerts -nodes -out client.key
chmod 600 client.key

OpenSSL asks for the .p12 password in each command.

📘

About -legacy: the .p12 file uses an encryption format that OpenSSL 3 only opens with the -legacy flag. If you use OpenSSL 1.1, remove the flag.

Check the certificate and its expiration date:

openssl x509 -in client.crt -noout -subject -enddate

Step 2: Test the connection

Before changing your application, test with cURL. If the token is returned, the certificate is working.

curl https://api.somossimpay.com.br/v2/finance/auth-token/ \
  --cert client.crt \
  --key client.key \
  -H "Content-Type: application/json" \
  -d '{"client_id":"your-client-id","client_secret":"your-client-secret"}'

Using the .p12 file directly:

curl https://api.somossimpay.com.br/v2/finance/auth-token/ \
  --cert-type P12 \
  --cert "client.p12:your-p12-password" \
  -H "Content-Type: application/json" \
  -d '{"client_id":"your-client-id","client_secret":"your-client-secret"}'

Replace https://api.somossimpay.com.br with the API address you already use.

Step 3: Use it in your application

Load the certificate once, when the application starts, and reuse the same HTTP client for every request. Keep sending the Authorization and hmac headers exactly as today.

Examples by language

Python (requests)

import os
import requests

session = requests.Session()
session.cert = (os.environ["MTLS_CERT_PATH"], os.environ["MTLS_KEY_PATH"])  # client.crt, client.key

response = session.post(
    "https://api.somossimpay.com.br/v2/finance/auth-token/",
    json={
        "client_id": os.environ["CLIENT_ID"],
        "client_secret": os.environ["CLIENT_SECRET"],
    },
    timeout=30,
)
response.raise_for_status()
access_token = response.json()["access_token"]

Node.js (https / axios)

const fs = require('fs');
const https = require('https');
const axios = require('axios');

const httpsAgent = new https.Agent({
  cert: fs.readFileSync(process.env.MTLS_CERT_PATH), // client.crt
  key: fs.readFileSync(process.env.MTLS_KEY_PATH),   // client.key
  keepAlive: true,
});

const api = axios.create({
  baseURL: 'https://api.somossimpay.com.br',
  httpsAgent,
  timeout: 30000,
});

async function getToken() {
  const { data } = await api.post('/v2/finance/auth-token/', {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
  });
  return data.access_token;
}
📘

Use the PEM files (cert and key) in Node.js. Passing the .p12 file in the pfx option fails on Node.js 17 or later with Unsupported PKCS12 PFX data, because of the legacy encryption mentioned in Step 1.

Java (11+, java.net.http)

import java.io.FileInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

public class MtlsClient {

    public static void main(String[] args) throws Exception {
        char[] password = System.getenv("MTLS_P12_PASSWORD").toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream in = new FileInputStream(System.getenv("MTLS_P12_PATH"))) {
            keyStore.load(in, password);
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, password);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, null);

        HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();

        String body = "{\"client_id\":\"" + System.getenv("CLIENT_ID")
                + "\",\"client_secret\":\"" + System.getenv("CLIENT_SECRET") + "\"}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.somossimpay.com.br/v2/finance/auth-token/"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
    }
}

C# (.NET 6+)

using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;

var certificate = new X509Certificate2(
    Environment.GetEnvironmentVariable("MTLS_P12_PATH"),
    Environment.GetEnvironmentVariable("MTLS_P12_PASSWORD"));

var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);

// Create once and reuse for the whole application
var client = new HttpClient(handler) { BaseAddress = new Uri("https://api.somossimpay.com.br") };

var response = await client.PostAsJsonAsync("/v2/finance/auth-token/", new
{
    client_id = Environment.GetEnvironmentVariable("CLIENT_ID"),
    client_secret = Environment.GetEnvironmentVariable("CLIENT_SECRET"),
});
response.EnsureSuccessStatusCode();

PHP (cURL)

<?php

$ch = curl_init('https://api.somossimpay.com.br/v2/finance/auth-token/');

curl_setopt_array($ch, [
    CURLOPT_SSLCERT        => getenv('MTLS_CERT_PATH'), // client.crt
    CURLOPT_SSLKEY         => getenv('MTLS_KEY_PATH'),  // client.key
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS     => json_encode([
        'client_id'     => getenv('CLIENT_ID'),
        'client_secret' => getenv('CLIENT_SECRET'),
    ]),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);

$response = curl_exec($ch);
if ($response === false) {
    throw new Exception('Connection error: ' . curl_error($ch));
}
curl_close($ch);

Go

package main

import (
	"bytes"
	"crypto/tls"
	"net/http"
	"os"
	"time"
)

func main() {
	cert, err := tls.LoadX509KeyPair(os.Getenv("MTLS_CERT_PATH"), os.Getenv("MTLS_KEY_PATH"))
	if err != nil {
		panic(err)
	}

	client := &http.Client{
		Timeout: 30 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
		},
	}

	body := []byte(`{"client_id":"your-client-id","client_secret":"your-client-secret"}`)
	resp, err := client.Post("https://api.somossimpay.com.br/v2/finance/auth-token/", "application/json", bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}

Postman

  1. Open Settings → Certificates → Client certificates → Add certificate.
  2. In Host, type the API address without https:// (for example api.example.com).
  3. Select client.crt in CRT file and client.key in KEY file.
  4. Save. Postman sends the certificate on every request to that host, and your token and HMAC scripts keep working.

Renewal and revocation

  • The certificate is valid for 365 days. Write down the expiration date (openssl x509 -in client.crt -noout -enddate) and set an alert at least 30 days before it.
  • To renew, send a new request to [email protected] with the same information. Install the new certificate before the old one expires.
  • If the .p12 file, its password or the private key may have been exposed, contact [email protected] immediately so we revoke the certificate and issue a new one.

Security best practices

  • Keep the .p12 file, its password and the private key in a secret manager (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault) or in protected files readable only by the application user.
  • Never commit the certificate or the key to a repository, and never send them by chat or e-mail.
  • Use the certificate only in server-to-server integrations. Never ship it inside a mobile app, a front-end or any software installed on end-user devices.
  • Keep the certificate password separate from the certificate file.
  • Do not disable server certificate validation (verify=False, rejectUnauthorized: false, -k) to make the connection work.

Troubleshooting

SymptomLikely causeWhat to do
TLS handshake error, certificate required, alert handshake failure or connection closed without an HTTP responseThe certificate is not being sentCheck that the HTTP client is configured with the certificate and key, as in the examples.
Error with certificate expired or bad certificateExpired certificate, or issued for another environmentCheck the dates with openssl x509 -noout -dates and use the certificate issued for this environment.
error:0308010C:digital envelope routines::unsupported or Unsupported PKCS12 PFX dataOpenSSL 3 or Node.js 17+ reading the .p12 fileConvert with the -legacy flag and use the PEM files, as in Step 1.
Mac verify error: invalid password?Wrong .p12 passwordCheck the password received with the certificate.
unable to set private key file / key values mismatchKey file does not belong to the certificate, or is still encryptedExport the key again with -nodes from the same .p12 file.
401 UnauthorizedThe connection passed mTLS; the token or HMAC is invalidFollow the Auth Token and HMAC Documentation pages.

Related Documentation