crossbind
GitHub
← Todas as bibliotecas

OpenSSL

TLS e primitivas criptográficas.

Instalação

Roda em navegadores; o Node.js e os ambientes de execução edge usam o mesmo pacote. Compilado para wasm32, com uma só thread e multithread.

shell
npm install @crossbind/port-openssl-wasm@beta
crossbind.config.js
import opensslWasm from '@crossbind/port-openssl-wasm/crossbind.config.js';
 
export default {
dependencies: [opensslWasm],
paths: { config: import.meta.url },
};
main.js
import { initNative, X509_get_subject_name } from '@crossbind/port-openssl/openssl/x509.h';
 
await initNative();

O próprio crossbind vem com o seu plugin de bundler; Plugins de bundlers cobre Vite, Webpack, Rspack, Rsbuild, Rollup, esbuild, Bun e Next.js.

O OpenSSL 4 no seu navegador: certificados, TLS e arquivos .p12 que o WebCrypto não trata

O WebCrypto calcula hashes, assina e criptografa, mas não lê certificados, não abre arquivos .p12 e não fala TLS. Estes apps rodam o próprio OpenSSL 4.1.1, compilado pelo crossbind: eles criam chaves e certificados, incluindo os pós-quânticos ML-DSA, rodam um handshake TLS 1.3 entre dois endpoints OpenSSL na aba com a troca de chaves híbrida ML-KEM padrão do OpenSSL e o Encrypted Client Hello, e abrem arquivos .p12, até os antigos RC2-40. O OpenSSL é Apache-2.0. A primeira execução baixa 4,2 MB de WebAssembly uma única vez; todos os apps desta página o compartilham, e nada é enviado.

APP 01

Crie uma chave e um certificado, ou leia qualquer PEM

Gere uma chave RSA, ECDSA, Ed25519 ou ML-DSA pós-quântica, depois um certificado autoassinado ou uma solicitação de assinatura de certificado para ela, e leia de volta o que o OpenSSL escreveu, do jeito que o openssl x509 -text imprime. Ou cole um certificado, uma cadeia, uma solicitação ou uma chave para inspecioná-los. O WebCrypto cria chaves, mas não lê certificados: aqui, o próprio OpenSSL roda na aba, e a chave privada nunca é enviada a lugar nenhum.

As chaves RSA demoram mais: encontrar os primos delas é trabalho aleatório. O ML-DSA-65 é a assinatura pós-quântica da FIPS 204; os certificados dele são para experimentos.

Roda o OpenSSL 4.1.1, sob a licença Apache-2.0: código-fonte · licença · receita de compilação
Gere uma chave e um certificado, ou inspecione a cadeia de exemplo.
MOSTRAR O CÓDIGO
src/support/pki.h
// src/support/pki.h, called by src/native/cert_studio.h (excerpt)
EVP_PKEY* key = EVP_PKEY_Q_keygen(nullptr, nullptr, "ML-DSA-65");
X509* cert = X509_new();
X509_set_version(cert, X509_VERSION_3);
X509_set_subject_name(cert, subject);
X509_set_issuer_name(cert, subject); // self-signed
X509_gmtime_adj(X509_getm_notBefore(cert), 0);
X509_time_adj_ex(X509_getm_notAfter(cert), days, 0, nullptr);
X509_set_pubkey(cert, key);
addExtension(cert, nullptr, NID_subject_alt_name, "DNS:localhost,IP:127.0.0.1");
addExtension(cert, nullptr, NID_subject_key_identifier, "hash");
X509_sign(cert, key, nullptr); // Ed25519 and ML-DSA take no digest
X509_print_ex(text, cert, CLI_NAME_FLAGS, X509_FLAG_COMPAT);
main.js
const m = await initNative();
const studio = await new m.CertStudio();
const key = await studio.generateKey('ML-DSA-65');
const pem = await studio.selfSign(key, '/CN=localhost', 'DNS:localhost,IP:127.0.0.1', 30, '', '', 0);
const [cert] = JSON.parse(await studio.inspect(pem));
// cert.signature: 'ML-DSA-65', cert.selfSigned: true
// cert.text: what `openssl x509 -text -noout` prints for it
APP 02

Um handshake TLS entre dois endpoints OpenSSL, nesta aba

Um cliente e um servidor OpenSSL 4 fazem o handshake por buffers de memória enquanto esta página carrega cada byte entre eles e lista cada mensagem. Veja a troca de chaves híbrida pós-quântica que o OpenSSL escolhe por padrão, esconda o nome do servidor com o Encrypted Client Hello ou inverta um bit na rede e veja o cliente recusá-lo. Uma página web não consegue abrir as próprias conexões TLS, então as duas pontas rodam aqui; o HTTPS desta página é o TLS do navegador, não o do OpenSSL.

O certificado do servidor é emitido para secret.example e public.example por uma CA em que o cliente confia, tudo criado no módulo na primeira execução de cada tipo de chave. Chaves RSA levam alguns segundos.

Roda o OpenSSL 4.1.1, sob a licença Apache-2.0: código-fonte · licença · receita de compilação
Faça o handshake para ver cada mensagem dele e o que alguém que observa a rede veria.
MOSTRAR O CÓDIGO
src/support/tls_run.h
// src/support/tls_run.h (excerpt)
SSL_set_bio(client.ssl, client.in, client.out); // memory BIOs, no sockets
SSL_set_bio(server.ssl, server.in, server.out);
SSL_set_msg_callback(client.ssl, traceMessage); // every message, as it is read
SSL_set_msg_callback(server.ssl, traceMessage);
SSL_set_tlsext_host_name(client.ssl, "secret.example");
SSL_set1_host(client.ssl, "secret.example"); // check the certificate's name
for (int round = 0; round < 8 && !(client.done && server.done); round += 1) {
step(client); // SSL_do_handshake until it waits
carry(client.out, server.in, true, wire); // this code moves the bytes
step(server);
carry(server.out, client.in, false, wire);
}
SSL_get0_group_name(client.ssl); // "X25519MLKEM768"
main.js
const m = await initNative();
const lab = await new m.TlsLab();
// server key, groups ('' is OpenSSL's default), TLS 1.2 only, ECH, flip a bit
const run = JSON.parse(await lab.handshake('ED25519', '', false, true, false));
// run.version: 'TLSv1.3', run.group: 'X25519MLKEM768'
// run.ech.status: 'success', run.serverNames: ['public.example']
// run.secretNameOnWire: 0, the real name is in none of the bytes sent
APP 03

Abra um arquivo .p12 ou .pfx, e crie um

Escolha um arquivo .p12 ou .pfx e digite a senha dele: a chave, o certificado e a cadeia saem em PEM, com a cifra e o MAC que protegem cada parte, nomeados como o openssl pkcs12 -info os nomeia. Arquivos escritos pelo OpenSSL 1.1.1 e por outras ferramentas antigas usam RC2-40 e 3DES, que o OpenSSL 3 e posteriores mantêm em um provider legado; esta compilação o traz e só o carrega para esses arquivos. O arquivo é lido nesta aba e não é enviado.

nenhum arquivo escolhido

Um exemplo é criado no módulo: uma chave P-256 e um certificado autoassinado para sample.example, empacotados com a senha “sample”, como o openssl pkcs12 -export os escreve, com ou sem -legacy.

Roda o OpenSSL 4.1.1, sob a licença Apache-2.0: código-fonte · licença · receita de compilação
Abra um arquivo .p12 ou .pfx, ou teste um exemplo, para ver o que tem dentro.
MOSTRAR O CÓDIGO
src/native/pfx_tool.h
// src/native/pfx_tool.h and src/support/pkcs12_info.h (excerpt)
PKCS12* p12 = d2i_PKCS12_bio(in, nullptr);
if (PKCS12_verify_mac(p12, password.c_str(), -1) != 1) throw std::runtime_error("wrong password");
if (!PKCS12_parse(p12, password.c_str(), &key, &cert, &chain)) {
// error:0308010C:digital envelope routines::unsupported: RC2-40 is in the legacy provider.
// Loading a provider by name turns off the automatic default one, so load that first, once.
OSSL_PROVIDER_load(nullptr, "default");
OSSL_PROVIDER* legacy = OSSL_PROVIDER_load(nullptr, "legacy");
PKCS12_parse(p12, password.c_str(), &key, &cert, &chain);
OSSL_PROVIDER_unload(legacy);
}
// and back, as OpenSSL 3 and later write it by default
PKCS12_create_ex2(password.c_str(), name, key, cert, chain, NID_aes_256_cbc, NID_aes_256_cbc,
PKCS12_DEFAULT_ITER, -1, 0, nullptr, nullptr, nullptr, nullptr);
PKCS12_set_mac(p12, password.c_str(), -1, nullptr, 0, PKCS12_DEFAULT_ITER, EVP_sha256());
main.js
const m = await initNative();
const pfx = await new m.PfxTool();
const bytes = new Uint8Array(await file.arrayBuffer());
const base64 = btoa(String.fromCharCode(...bytes)); // fine for a .p12; chunk big files
const opened = JSON.parse(await pfx.unpack(base64, password));
// opened.safes: the lines openssl pkcs12 -info prints for the file
// opened.legacyProvider: true for RC2-40 files; opened.keyPem, opened.certPem, opened.chain

Exemplos

Cada um é um pequeno arquivo de cabeçalho C++ e o JavaScript que o chama, com o que ele imprimiu quando o site foi compilado. A aba Só JavaScript faz o mesmo com os próprios arquivos de cabeçalho de OpenSSL e sem arquivo C++. O último é um programa C++ completo, compilado para WASI.

Leia um certificado como openssl x509 -text

O que as pessoas abrem um certificado para ver, a partir de C++: PEM_read_bio_X509 o analisa, X509_NAME_print_ex escreve o titular (subject) e o emissor (issuer), ASN1_TIME_print_ex, a validade, X509V3_EXT_print, os nomes alternativos, X509_check_host compara um nome de host do jeito que um cliente TLS faz e X509_digest calcula a impressão digital SHA-256. O WebCrypto não tem parser de X.509.

src/native/certificate.h
#pragma once
 
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
 
#include <stdexcept>
#include <string>
 
// A certificate read from PEM text, and the fields `openssl x509 -text` shows first.
class Certificate {
public:
explicit Certificate(const std::string& pem) {
const std::string text = unindent(pem);
BIO* input = BIO_new_mem_buf(text.data(), static_cast<int>(text.size()));
cert = PEM_read_bio_X509(input, nullptr, nullptr, nullptr);
BIO_free(input);
if (!cert) fail("not a PEM certificate");
}
~Certificate() { X509_free(cert); }
Certificate(const Certificate&) = delete;
Certificate& operator=(const Certificate&) = delete;
 
// Names as RFC 2253 writes them, most specific first: "CN=example.com,O=Example,C=US".
std::string subject() const { return distinguishedName(X509_get_subject_name(cert)); }
std::string issuer() const { return distinguishedName(X509_get_issuer_name(cert)); }
 
// "2026-05-30 00:00:00Z"
std::string notBefore() const { return isoTime(X509_get0_notBefore(cert)); }
std::string notAfter() const { return isoTime(X509_get0_notAfter(cert)); }
 
// The subjectAltName extension as the CLI prints it: "DNS:example.com, IP Address:192.0.2.1".
std::string altNames() const {
const int index = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (index < 0) return "";
BIO* out = BIO_new(BIO_s_mem());
X509V3_EXT_print(out, X509_get_ext(cert, index), 0, 0);
return drain(out);
}
 
// "EC prime256v1", "RSA", "ED25519", "ML-DSA-65", ...
std::string keyType() const {
EVP_PKEY* key = X509_get0_pubkey(cert);
std::string type = EVP_PKEY_get0_type_name(key);
char group[80];
if (EVP_PKEY_get_group_name(key, group, sizeof group, nullptr)) type += std::string(" ") + group;
return type;
}
 
int keyBits() const { return EVP_PKEY_get_bits(X509_get0_pubkey(cert)); }
 
// Whether a TLS client would accept this certificate for the host name, wildcards included.
bool covers(const std::string& host) const { return X509_check_host(cert, host.data(), host.size(), 0, nullptr) == 1; }
 
// Issued by itself, with a signature its own key verifies.
bool selfSigned() const { return X509_self_signed(cert, 1) == 1; }
 
// The SHA-256 fingerprint, written like `openssl x509 -fingerprint -sha256`.
std::string sha256() const {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int size = 0;
if (!X509_digest(cert, EVP_sha256(), digest, &size)) fail("digest failed");
static const char hex[] = "0123456789ABCDEF";
std::string out;
for (unsigned int i = 0; i < size; i += 1) {
if (i) out += ':';
out += hex[digest[i] >> 4];
out += hex[digest[i] & 0x0F];
}
return out;
}
 
private:
X509* cert = nullptr;
 
// PEM lines must start in the first column; text pasted from YAML, JSON or an indented
// template literal often does not.
static std::string unindent(const std::string& text) {
std::string out;
bool lineStart = true;
for (const char character : text) {
if (lineStart && (character == ' ' || character == '\t')) continue;
out += character;
lineStart = character == '\n';
}
return out;
}
 
static std::string distinguishedName(const X509_NAME* value) {
BIO* out = BIO_new(BIO_s_mem());
X509_NAME_print_ex(out, value, 0, XN_FLAG_RFC2253);
return drain(out);
}
 
static std::string isoTime(const ASN1_TIME* value) {
BIO* out = BIO_new(BIO_s_mem());
ASN1_TIME_print_ex(out, value, ASN1_DTFLGS_ISO8601);
return drain(out);
}
 
static std::string drain(BIO* out) {
char* data = nullptr;
const long size = BIO_get_mem_data(out, &data);
std::string text(data, size > 0 ? static_cast<size_t>(size) : 0);
BIO_free(out);
return text;
}
 
// OpenSSL queues its errors; the first one says what went wrong.
[[noreturn]] static void fail(const std::string& what) {
char reason[256] = "";
const unsigned long code = ERR_get_error();
if (code) ERR_error_string_n(code, reason, sizeof reason);
ERR_clear_error();
throw std::runtime_error(code ? what + ": " + reason : what);
}
};
main.js
import { initNative, Certificate } from './native/certificate.h';
 
await initNative();
// A test certificate for shop.example.com, issued by a test CA.
const pem = `-----BEGIN CERTIFICATE-----
MIICIjCCAcigAwIBAgICEAEwCgYIKoZIzj0EAwIwQzELMAkGA1UEBhMCVVMxFTAT
BgNVBAoMDEV4YW1wbGUgU2hvcDEdMBsGA1UEAwwURXhhbXBsZSBTaG9wIFRlc3Qg
Q0EwHhcNMjYwMzAxMDAwMDAwWhcNMjYwNTMwMDAwMDAwWjA/MQswCQYDVQQGEwJV
UzEVMBMGA1UECgwMRXhhbXBsZSBTaG9wMRkwFwYDVQQDDBBzaG9wLmV4YW1wbGUu
Y29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZR6VvLcXeY1MN21YB02ab2Qc
OzohfHo98QuwSjxUrEEni8Yj0oXx53RyQtlAUlDkddzJOt6ldz90XgKXuWIOGKOB
rzCBrDAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggr
BgEFBQcDATA3BgNVHREEMDAughBzaG9wLmV4YW1wbGUuY29tghR3d3cuc2hvcC5l
eGFtcGxlLmNvbYcEwAACCjAdBgNVHQ4EFgQU1y3zWDMZI93FAyhp8QnFGfs10k4w
HwYDVR0jBBgwFoAUPExNl7RaXtxsfW/VdAj+Rlc4gpIwCgYIKoZIzj0EAwIDSAAw
RQIgZtZXDYEsjrz91CjoZyFE5coj51aR5sZi/wKllD1qYq8CIQCOKkQWCapO2G/A
p1aRCXKO+JxjPWGnkYe0B8RLljl9Pw==
-----END CERTIFICATE-----`;
const cert = await new Certificate(pem);
console.log(await cert.subject());
console.log('issued by', await cert.issuer());
console.log('valid', await cert.notBefore(), 'to', await cert.notAfter());
console.log(await cert.altNames());
console.log(`${await cert.keyType()} ${await cert.keyBits()} bits, self-signed ${await cert.selfSigned()}`);
for (const host of ['www.shop.example.com', 'shop.example.org']) console.log(host, await cert.covers(host));
console.log(await cert.sha256());
IMPRIMEa primeira execução baixa 4,2 MB
CN=shop.example.com,O=Example Shop,C=US
issued by CN=Example Shop Test CA,O=Example Shop,C=US
valid 2026-03-01 00:00:00Z to 2026-05-30 00:00:00Z
DNS:shop.example.com, DNS:www.shop.example.com, IP Address:192.0.2.10
EC prime256v1 256 bits, self-signed false
www.shop.example.com true
shop.example.org false
68:2D:81:9E:75:7E:2C:15:C1:92:FB:84:3D:BE:AA:99:B4:54:58:D4:5F:A3:F3:3A:C8:13:1E:9D:03:9C:89:3C

Hash e HMAC

EVP_Q_digest calcula o hash de dados que já estão na memória com qualquer digest pelo nome, EVP_DigestUpdate os recebe em pedaços à medida que um arquivo ou um download chega, e EVP_Q_mac cria o HMAC que as assinaturas de webhooks e de requisições de API usam. O WebCrypto para no SHA-1 e no SHA-2; aqui, SHA-3 e BLAKE2 vêm do OpenSSL. Cada linha é o vetor de teste publicado do padrão dela.

src/native/hashing.h
#pragma once
 
#include <openssl/err.h>
#include <openssl/evp.h>
 
#include <stdexcept>
#include <string>
 
// Digests and HMAC by algorithm name: "SHA256", "SHA3-256", "BLAKE2B-512", "SHA512-256", "SM3" or
// any other digest OpenSSL's default provider has. Text goes in as its UTF-8 bytes.
class Digest {
public:
// Streaming: update with the data in as many pieces as it arrives in, then read the digest once.
explicit Digest(const std::string& algorithm) : context(EVP_MD_CTX_new()) {
EVP_MD* md = EVP_MD_fetch(nullptr, algorithm.c_str(), nullptr);
const bool ready = md && EVP_DigestInit_ex2(context, md, nullptr);
EVP_MD_free(md);
if (!ready) fail("unknown digest " + algorithm);
}
~Digest() { EVP_MD_CTX_free(context); }
Digest(const Digest&) = delete;
Digest& operator=(const Digest&) = delete;
 
void update(const std::string& data) {
if (!EVP_DigestUpdate(context, data.data(), data.size())) fail("digest update failed");
}
 
std::string hex() {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int size = 0;
if (!EVP_DigestFinal_ex(context, digest, &size)) fail("digest already read");
return toHex(digest, size);
}
 
// One call for data that is already in memory.
static std::string of(const std::string& algorithm, const std::string& data) {
unsigned char digest[EVP_MAX_MD_SIZE];
size_t size = 0;
if (!EVP_Q_digest(nullptr, algorithm.c_str(), nullptr, data.data(), data.size(), digest, &size)) fail("unknown digest " + algorithm);
return toHex(digest, size);
}
 
// HMAC with the named digest, as webhooks and API request signatures use it.
static std::string hmac(const std::string& algorithm, const std::string& key, const std::string& data) {
unsigned char mac[EVP_MAX_MD_SIZE];
size_t size = 0;
const auto* bytes = reinterpret_cast<const unsigned char*>(data.data());
if (!EVP_Q_mac(nullptr, "HMAC", nullptr, algorithm.c_str(), nullptr, key.data(), key.size(), bytes, data.size(), mac, sizeof mac, &size)) {
fail("HMAC with " + algorithm + " failed");
}
return toHex(mac, size);
}
 
private:
EVP_MD_CTX* context;
 
static std::string toHex(const unsigned char* data, size_t size) {
static const char hex[] = "0123456789abcdef";
std::string out;
for (size_t i = 0; i < size; i += 1) {
out += hex[data[i] >> 4];
out += hex[data[i] & 0x0F];
}
return out;
}
 
[[noreturn]] static void fail(const std::string& what) {
ERR_clear_error();
throw std::runtime_error(what);
}
};
main.js
import { initNative, Digest } from './native/hashing.h';
 
await initNative();
for (const algorithm of ['SHA256', 'SHA3-256', 'BLAKE2B-512']) console.log(algorithm, await Digest.of(algorithm, 'abc'));
console.log('HMAC-SHA256', await Digest.hmac('SHA256', 'Jefe', 'what do ya want for nothing?'));
 
// A million "a" in ten pieces, the way a file arrives.
const digest = await new Digest('SHA256');
for (let piece = 0; piece < 10; piece += 1) await digest.update('a'.repeat(100000));
console.log('streamed SHA256', await digest.hex());
IMPRIMEa primeira execução baixa 4,2 MB
SHA256 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
SHA3-256 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
BLAKE2B-512 ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923
HMAC-SHA256 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
streamed SHA256 cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0

Criptografe e autentique com AES-256-GCM

EVP_CipherInit_ex2 com AES-256-GCM criptografa e autentica em uma única passada; EVP_CTRL_AEAD_GET_TAG lê a tag de 16 bytes, e, com EVP_CTRL_AEAD_SET_TAG, a descriptografia recusa qualquer coisa que tenha mudado, incluindo os dados associados que trafegam às claras. A saída é o texto cifrado seguido da tag, o layout que o WebCrypto lê.

src/native/aes_gcm.h
#pragma once
 
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
 
#include <memory>
#include <stdexcept>
#include <string>
 
// AES in GCM mode: encryption and an authentication tag in one pass. The key is 16, 24 or 32 bytes
// (AES-128, -192 or -256) and every message needs a fresh 12-byte nonce; reusing a nonce with the
// same key gives the plaintext away.
class AesGcm {
public:
explicit AesGcm(const std::string& keyHex) : key(fromHex(keyHex)) {
if (key.size() != 16 && key.size() != 24 && key.size() != 32) throw std::invalid_argument("AES keys are 16, 24 or 32 bytes");
}
~AesGcm() { OPENSSL_cleanse(&key[0], key.size()); }
AesGcm(const AesGcm&) = delete;
AesGcm& operator=(const AesGcm&) = delete;
 
// The ciphertext followed by the 16-byte tag, in hex: the layout WebCrypto's AES-GCM uses too.
// `aad` is authenticated but not encrypted, such as a record id the ciphertext belongs to.
std::string encrypt(const std::string& nonceHex, const std::string& plaintext, const std::string& aad) {
Context context(start(1, nonceHex, aad));
std::string out(plaintext.size() + TAG_SIZE, '\0');
int written = 0;
int last = 0;
if (!EVP_EncryptUpdate(context.get(), bytes(out), &written, bytes(plaintext), static_cast<int>(plaintext.size()))
|| !EVP_EncryptFinal_ex(context.get(), bytes(out) + written, &last)
|| !EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_AEAD_GET_TAG, TAG_SIZE, bytes(out) + written + last)) {
fail("encryption failed");
}
return toHex(out);
}
 
// Throws unless the tag matches, so a changed byte anywhere in the ciphertext, the tag, the nonce
// or the AAD is refused, never decrypted to garbage.
std::string decrypt(const std::string& nonceHex, const std::string& sealedHex, const std::string& aad) {
std::string sealed = fromHex(sealedHex);
if (sealed.size() < TAG_SIZE) throw std::invalid_argument("shorter than a tag");
const size_t size = sealed.size() - TAG_SIZE;
Context context(start(0, nonceHex, aad));
std::string out(size, '\0');
int written = 0;
int last = 0;
if (!EVP_DecryptUpdate(context.get(), bytes(out), &written, bytes(sealed), static_cast<int>(size))
|| !EVP_CIPHER_CTX_ctrl(context.get(), EVP_CTRL_AEAD_SET_TAG, TAG_SIZE, bytes(sealed) + size)
|| EVP_DecryptFinal_ex(context.get(), bytes(out) + written, &last) != 1) {
OPENSSL_cleanse(&out[0], out.size());
fail("authentication failed: wrong key, nonce or AAD, or the data was changed");
}
return out;
}
 
private:
static constexpr int TAG_SIZE = 16;
struct Free {
void operator()(EVP_CIPHER_CTX* context) const { EVP_CIPHER_CTX_free(context); }
};
using Context = std::unique_ptr<EVP_CIPHER_CTX, Free>;
 
std::string key;
 
EVP_CIPHER_CTX* start(int encrypting, const std::string& nonceHex, const std::string& aad) {
const std::string nonce = fromHex(nonceHex);
if (nonce.size() != 12) throw std::invalid_argument("GCM nonces here are 12 bytes");
const char* name = key.size() == 32 ? "AES-256-GCM" : key.size() == 24 ? "AES-192-GCM" : "AES-128-GCM";
EVP_CIPHER* cipher = EVP_CIPHER_fetch(nullptr, name, nullptr);
EVP_CIPHER_CTX* context = EVP_CIPHER_CTX_new();
int ignored = 0;
const bool ready = cipher && context && EVP_CipherInit_ex2(context, cipher, bytes(key), bytes(nonce), encrypting, nullptr)
&& (aad.empty() || EVP_CipherUpdate(context, nullptr, &ignored, bytes(aad), static_cast<int>(aad.size())));
EVP_CIPHER_free(cipher);
if (!ready) {
EVP_CIPHER_CTX_free(context);
fail("cannot start AES-GCM");
}
return context;
}
 
static unsigned char* bytes(std::string& data) { return reinterpret_cast<unsigned char*>(&data[0]); }
static const unsigned char* bytes(const std::string& data) { return reinterpret_cast<const unsigned char*>(data.data()); }
 
static std::string toHex(const std::string& data) {
static const char hex[] = "0123456789abcdef";
std::string out;
for (const unsigned char byte : data) {
out += hex[byte >> 4];
out += hex[byte & 0x0F];
}
return out;
}
 
static std::string fromHex(const std::string& hex) {
const auto nibble = [](char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
throw std::invalid_argument("not hex");
};
if (hex.size() % 2) throw std::invalid_argument("hex has an odd length");
std::string out(hex.size() / 2, '\0');
for (size_t i = 0; i < out.size(); i += 1) out[i] = static_cast<char>(nibble(hex[2 * i]) * 16 + nibble(hex[2 * i + 1]));
return out;
}
 
[[noreturn]] static void fail(const std::string& what) {
ERR_clear_error();
throw std::runtime_error(what);
}
};
main.js
import { initNative, AesGcm } from './native/aes_gcm.h';
 
await initNative();
// A fixed test key and nonce, so the output repeats. Use 32 random bytes as the key, and never
// use a nonce twice with it.
const gcm = await new AesGcm('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
const nonce = '000000000000000000000001';
const sealed = await gcm.encrypt(nonce, 'meet at the north gate at 7', 'message-1');
console.log('ciphertext', sealed.slice(0, -32));
console.log('tag', sealed.slice(-32));
console.log(await gcm.decrypt(nonce, sealed, 'message-1'));
try {
await gcm.decrypt(nonce, sealed, 'message-2');
} catch (error) {
console.log('refused:', error.message);
}
IMPRIMEa primeira execução baixa 4,2 MB
ciphertext 78b3da886495443e7a46341982c948837dbf7b3510d774e5072034
tag 4f8c8f6e9e6177f201ed83f957fbe6d7
meet at the north gate at 7
refused: std::runtime_error: authentication failed: wrong key, nonce or AAD, or the data was changed

Gere uma chave, assine e verifique

EVP_PKEY_Q_keygen cria um par de chaves, PEM_write_bio_PUBKEY exporta a metade pública dele, EVP_DigestSign assina e EVP_DigestVerify verifica só com esse PEM. As mesmas chamadas assinam com ECDSA P-256, Ed25519 e ML-DSA-65, a assinatura pós-quântica do FIPS 204. As chaves são aleatórias, então o exemplo imprime o que continua igual: tamanhos, força e os veredictos.

src/native/signing.h
#pragma once
 
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
 
#include <stdexcept>
#include <string>
 
// A fresh key pair, signatures with it, and verification with nothing but the public key's PEM, as
// the receiving side does it. "P-256" signs with ECDSA over SHA-256, "RSA-2048" with PKCS#1 v1.5
// over SHA-256; "ED25519" and the post-quantum "ML-DSA-44", "ML-DSA-65" and "ML-DSA-87" sign the
// message itself.
class KeyPair {
public:
explicit KeyPair(const std::string& algorithm) : key(generate(algorithm)) {
if (!key) fail("cannot generate a " + algorithm + " key");
}
~KeyPair() { EVP_PKEY_free(key); }
KeyPair(const KeyPair&) = delete;
KeyPair& operator=(const KeyPair&) = delete;
 
// "EC", "RSA", "ED25519", "ML-DSA-65", ...
std::string type() const { return EVP_PKEY_get0_type_name(key); }
 
// The strength OpenSSL rates the key at, in bits.
int securityBits() const { return EVP_PKEY_get_security_bits(key); }
 
// The largest signature the key makes, in bytes.
int maxSignatureSize() const { return EVP_PKEY_get_size(key); }
 
// "-----BEGIN PUBLIC KEY-----": what you hand to whoever verifies.
std::string publicKeyPem() const {
BIO* out = BIO_new(BIO_s_mem());
PEM_write_bio_PUBKEY(out, key);
return drain(out);
}
 
// "-----BEGIN PRIVATE KEY-----", unencrypted PKCS#8: keep it to yourself.
std::string privateKeyPem() const {
BIO* out = BIO_new(BIO_s_mem());
PEM_write_bio_PrivateKey(out, key, nullptr, nullptr, 0, nullptr, nullptr);
return drain(out);
}
 
// The signature, in hex.
std::string sign(const std::string& message) const {
EVP_MD_CTX* context = EVP_MD_CTX_new();
size_t size = 0;
std::string signature;
bool signed_ = EVP_DigestSignInit_ex(context, nullptr, digestFor(key), nullptr, nullptr, key, nullptr) == 1
&& EVP_DigestSign(context, nullptr, &size, bytes(message), message.size()) == 1;
if (signed_) {
signature.resize(size);
signed_ = EVP_DigestSign(context, reinterpret_cast<unsigned char*>(&signature[0]), &size, bytes(message), message.size()) == 1;
signature.resize(size);
}
EVP_MD_CTX_free(context);
if (!signed_) fail("signing failed");
return toHex(signature);
}
 
static bool verify(const std::string& publicKeyPem, const std::string& message, const std::string& signatureHex) {
BIO* input = BIO_new_mem_buf(publicKeyPem.data(), static_cast<int>(publicKeyPem.size()));
EVP_PKEY* publicKey = PEM_read_bio_PUBKEY(input, nullptr, nullptr, nullptr);
BIO_free(input);
if (!publicKey) fail("not a PEM public key");
const std::string signature = fromHex(signatureHex);
EVP_MD_CTX* context = EVP_MD_CTX_new();
const bool valid = EVP_DigestVerifyInit_ex(context, nullptr, digestFor(publicKey), nullptr, nullptr, publicKey, nullptr) == 1
&& EVP_DigestVerify(context, bytes(signature), signature.size(), bytes(message), message.size()) == 1;
EVP_MD_CTX_free(context);
EVP_PKEY_free(publicKey);
ERR_clear_error();
return valid;
}
 
private:
EVP_PKEY* key;
 
static EVP_PKEY* generate(const std::string& algorithm) {
if (algorithm == "P-256") return EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", "P-256");
if (algorithm == "RSA-2048") return EVP_PKEY_Q_keygen(nullptr, nullptr, "RSA", static_cast<size_t>(2048));
return EVP_PKEY_Q_keygen(nullptr, nullptr, algorithm.c_str());
}
 
// ECDSA and RSA sign a digest of the message; Ed25519 and ML-DSA take the message whole.
static const char* digestFor(const EVP_PKEY* key) { return EVP_PKEY_is_a(key, "EC") || EVP_PKEY_is_a(key, "RSA") ? "SHA256" : nullptr; }
 
static const unsigned char* bytes(const std::string& data) { return reinterpret_cast<const unsigned char*>(data.data()); }
 
static std::string drain(BIO* out) {
char* data = nullptr;
const long size = BIO_get_mem_data(out, &data);
std::string text(data, size > 0 ? static_cast<size_t>(size) : 0);
BIO_free(out);
return text;
}
 
static std::string toHex(const std::string& data) {
static const char hex[] = "0123456789abcdef";
std::string out;
for (const unsigned char byte : data) {
out += hex[byte >> 4];
out += hex[byte & 0x0F];
}
return out;
}
 
static std::string fromHex(const std::string& hex) {
const auto nibble = [](char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
throw std::invalid_argument("not hex");
};
if (hex.size() % 2) throw std::invalid_argument("hex has an odd length");
std::string out(hex.size() / 2, '\0');
for (size_t i = 0; i < out.size(); i += 1) out[i] = static_cast<char>(nibble(hex[2 * i]) * 16 + nibble(hex[2 * i + 1]));
return out;
}
 
[[noreturn]] static void fail(const std::string& what) {
ERR_clear_error();
throw std::runtime_error(what);
}
};
main.js
import { initNative, KeyPair } from './native/signing.h';
 
await initNative();
const message = 'release 2.4.0, sha256 3a985da74fe225b2';
for (const algorithm of ['P-256', 'ED25519', 'ML-DSA-65']) {
const key = await new KeyPair(algorithm);
const publicKey = await key.publicKeyPem();
const signature = await key.sign(message);
const valid = await KeyPair.verify(publicKey, message, signature);
const altered = await KeyPair.verify(publicKey, message.replace('2.4.0', '2.4.1'), signature);
const size = await key.maxSignatureSize();
console.log(`${algorithm}: ${await key.type()}, ${await key.securityBits()}-bit security, signatures up to ${size} bytes, valid ${valid}, altered message ${altered}`);
}
IMPRIMEa primeira execução baixa 4,2 MB
P-256: EC, 128-bit security, signatures up to 72 bytes, valid true, altered message false
ED25519: ED25519, 128-bit security, signatures up to 64 bytes, valid true, altered message false
ML-DSA-65: ML-DSA-65, 192-bit security, signatures up to 3309 bytes, valid true, altered message false

Crie um certificado autoassinado para localhost

A pergunta mais feita sobre o OpenSSL, respondida em C++: X509_new, um número de série aleatório, X509V3_EXT_conf_nid para o subjectAltName que os navegadores comparam, e X509_sign com a chave que ele certifica, os campos que openssl req -x509 -addext subjectAltName=... escreve. A chave vem do exemplo de assinatura, e o exemplo do certificado lê o resultado de volta.

src/native/self_signed.h
#pragma once
 
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
 
#include <stdexcept>
#include <string>
 
// The certificate `openssl req -x509 -key key.pem -subj /CN=<name> -addext subjectAltName=<names>`
// makes: version 3, its own issuer, the alternative names and a subject key identifier, signed by
// the key it certifies. Browsers match the alternative names, not the common name.
class SelfSigned {
public:
// `altNames` as the CLI takes them, "DNS:localhost,IP:127.0.0.1"; the dates as ASN.1 times,
// "20260101000000Z".
static std::string create(const std::string& keyPem, const std::string& commonName, const std::string& altNames,
const std::string& notBefore, const std::string& notAfter) {
BIO* input = BIO_new_mem_buf(keyPem.data(), static_cast<int>(keyPem.size()));
EVP_PKEY* key = PEM_read_bio_PrivateKey(input, nullptr, nullptr, nullptr);
BIO_free(input);
if (!key) fail("not a PEM private key");
X509* cert = X509_new();
X509_NAME* subject = X509_NAME_new();
const auto* name = reinterpret_cast<const unsigned char*>(commonName.c_str());
const bool made = X509_set_version(cert, X509_VERSION_3) && randomSerial(cert)
&& X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_UTF8, name, -1, -1, 0)
&& X509_set_subject_name(cert, subject) && X509_set_issuer_name(cert, subject)
&& ASN1_TIME_set_string_X509(X509_getm_notBefore(cert), notBefore.c_str())
&& ASN1_TIME_set_string_X509(X509_getm_notAfter(cert), notAfter.c_str()) && X509_set_pubkey(cert, key)
&& extend(cert, NID_subject_alt_name, altNames) && extend(cert, NID_subject_key_identifier, "hash")
&& X509_sign(cert, key, EVP_PKEY_is_a(key, "EC") || EVP_PKEY_is_a(key, "RSA") ? EVP_sha256() : nullptr) > 0;
std::string pem;
if (made) {
BIO* out = BIO_new(BIO_s_mem());
PEM_write_bio_X509(out, cert);
char* data = nullptr;
const long size = BIO_get_mem_data(out, &data);
pem.assign(data, size > 0 ? static_cast<size_t>(size) : 0);
BIO_free(out);
}
X509_NAME_free(subject);
X509_free(cert);
EVP_PKEY_free(key);
if (!made) fail("cannot make the certificate");
return pem;
}
 
private:
// A random 159-bit serial, as the CLI picks: Firefox refuses a new certificate that repeats the
// issuer and serial of one it has seen, which fixed serials on regenerated certificates do.
static bool randomSerial(X509* cert) {
BIGNUM* serial = BN_new();
const bool ok = serial && BN_rand(serial, 159, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)
&& BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert));
BN_free(serial);
return ok;
}
 
static bool extend(X509* cert, int nid, const std::string& value) {
X509V3_CTX context;
X509V3_set_ctx(&context, cert, cert, nullptr, nullptr, 0);
X509_EXTENSION* extension = X509V3_EXT_conf_nid(nullptr, &context, nid, value.c_str());
const bool added = extension && X509_add_ext(cert, extension, -1);
X509_EXTENSION_free(extension);
return added;
}
 
[[noreturn]] static void fail(const std::string& what) {
char reason[256] = "";
const unsigned long code = ERR_get_error();
if (code) ERR_error_string_n(code, reason, sizeof reason);
ERR_clear_error();
throw std::runtime_error(code ? what + ": " + reason : what);
}
};
main.js
import { initNative, SelfSigned } from './native/self_signed.h';
import { KeyPair } from './native/signing.h';
import { Certificate } from './native/certificate.h';
 
await initNative();
const key = await new KeyPair('P-256');
const pem = await SelfSigned.create(await key.privateKeyPem(), 'localhost', 'DNS:localhost,IP:127.0.0.1', '20260101000000Z', '20270101000000Z');
console.log(pem.split('\n')[0]);
 
const cert = await new Certificate(pem);
console.log(await cert.subject(), await cert.altNames());
console.log('valid', await cert.notBefore(), 'to', await cert.notAfter());
console.log(`${await cert.keyType()} ${await cert.keyBits()} bits, self-signed ${await cert.selfSigned()}`);
for (const host of ['localhost', 'example.com']) console.log(host, await cert.covers(host));
IMPRIMEa primeira execução baixa 4,2 MB
-----BEGIN CERTIFICATE-----
CN=localhost DNS:localhost, IP Address:127.0.0.1
valid 2026-01-01 00:00:00Z to 2027-01-01 00:00:00Z
EC prime256v1 256 bits, self-signed true
localhost true
example.com false

Uma ferramenta de checksum sobre o OpenSSL

O WASI não tem bindings JavaScript: o programa é um main() que vincula o OpenSSL, compilado em um único .wasm e executado com o wasmtime. Este imprime digests de arquivos no formato do sha256sum com qualquer digest que o OpenSSL tenha, verifica uma lista de checksums do jeito que sha256sum -c faz e calcula o HMAC com que quem envia um webhook assina o payload.

crossbind.config.js
import opensslWasi from '@crossbind/port-openssl-wasi/crossbind.config.js';
 
export default {
general: { name: 'openssl-tool' },
dependencies: [opensslWasi],
// A separate output folder: crossbind 2.0.0-beta.60 stops with ENOENT at the end of a WASI build
// whose dependencies ship data (OpenSSL's CA certificates here) when output is the build folder.
paths: { config: import.meta.url, output: 'dist' },
};
src/native/main.cpp
// A checksum tool on OpenSSL for WASI: file digests in sha256sum's format, a check of a checksum
// list, and the HMAC a webhook sender signs a payload with.
// openssl-tool digest <algorithm> <file>... sha256, sha3-256, blake2b512, sm3, ... as OpenSSL names them
// openssl-tool check <list> "<sha256> <file>" lines, as sha256sum -c reads them
// openssl-tool hmac <algorithm> <key file> <file>...
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
 
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
 
namespace {
 
constexpr size_t CHUNK = 64 * 1024;
 
std::string hex(const unsigned char* data, size_t size) {
static const char digits[] = "0123456789abcdef";
std::string out;
for (size_t i = 0; i < size; i += 1) {
out += digits[data[i] >> 4];
out += digits[data[i] & 0x0F];
}
return out;
}
 
// Feeds a file to `update` in 64 KB pieces, so a file of any size fits in memory.
template <typename Update>
bool stream(const std::string& path, Update update) {
std::FILE* file = std::fopen(path.c_str(), "rb");
if (!file) {
std::fprintf(stderr, "openssl-tool: cannot open %s\n", path.c_str());
return false;
}
std::vector<unsigned char> buffer(CHUNK);
bool ok = true;
size_t read = 0;
while (ok && (read = std::fread(buffer.data(), 1, buffer.size(), file)) > 0) ok = update(buffer.data(), read);
ok = ok && !std::ferror(file);
std::fclose(file);
return ok;
}
 
// The file's digest in hex, or an empty string when the algorithm or the file is unknown.
std::string digest(const std::string& algorithm, const std::string& path) {
EVP_MD* md = EVP_MD_fetch(nullptr, algorithm.c_str(), nullptr);
EVP_MD_CTX* context = EVP_MD_CTX_new();
unsigned char value[EVP_MAX_MD_SIZE];
unsigned int size = 0;
bool ok = md && context && EVP_DigestInit_ex2(context, md, nullptr) == 1;
if (!md) std::fprintf(stderr, "openssl-tool: unknown digest %s\n", algorithm.c_str());
ok = ok && stream(path, [&](const unsigned char* data, size_t length) { return EVP_DigestUpdate(context, data, length) == 1; });
ok = ok && EVP_DigestFinal_ex(context, value, &size) == 1;
EVP_MD_CTX_free(context);
EVP_MD_free(md);
return ok ? hex(value, size) : "";
}
 
std::string hmac(const std::string& algorithm, const std::string& key, const std::string& path) {
EVP_MAC* mac = EVP_MAC_fetch(nullptr, "HMAC", nullptr);
EVP_MAC_CTX* context = mac ? EVP_MAC_CTX_new(mac) : nullptr;
OSSL_PARAM params[] = {OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, const_cast<char*>(algorithm.c_str()), 0), OSSL_PARAM_construct_end()};
unsigned char value[EVP_MAX_MD_SIZE];
size_t size = 0;
bool ok = context && EVP_MAC_init(context, reinterpret_cast<const unsigned char*>(key.data()), key.size(), params) == 1;
if (!ok) std::fprintf(stderr, "openssl-tool: cannot make an HMAC with %s\n", algorithm.c_str());
ok = ok && stream(path, [&](const unsigned char* data, size_t length) { return EVP_MAC_update(context, data, length) == 1; });
ok = ok && EVP_MAC_final(context, value, &size, sizeof value) == 1;
EVP_MAC_CTX_free(context);
EVP_MAC_free(mac);
return ok ? hex(value, size) : "";
}
 
int digestFiles(const std::string& algorithm, int count, char** paths) {
int status = 0;
for (int i = 0; i < count; i += 1) {
const std::string value = digest(algorithm, paths[i]);
if (value.empty()) status = 1;
else std::printf("%s %s\n", value.c_str(), paths[i]);
}
return status;
}
 
// Every line of the list is a SHA-256 in hex, two spaces (or a space and a star) and a file name.
int check(const std::string& list) {
std::ifstream file(list);
if (!file) {
std::fprintf(stderr, "openssl-tool: cannot open %s\n", list.c_str());
return 1;
}
int failed = 0;
std::string line;
while (std::getline(file, line)) {
if (line.size() < 67 || line[64] != ' ') continue;
const std::string expected = line.substr(0, 64);
const std::string name = line.substr(66);
const bool ok = digest("SHA256", name) == expected;
std::printf("%s: %s\n", name.c_str(), ok ? "OK" : "FAILED");
if (!ok) failed += 1;
}
if (failed) std::fprintf(stderr, "openssl-tool: WARNING: %d computed checksum%s did NOT match\n", failed, failed == 1 ? "" : "s");
return failed ? 1 : 0;
}
 
// The key file's trailing line break is not part of the key, as with most secrets saved by editors.
int hmacFiles(const std::string& algorithm, const std::string& keyPath, int count, char** paths) {
std::ifstream file(keyPath, std::ios::binary);
if (!file) {
std::fprintf(stderr, "openssl-tool: cannot open %s\n", keyPath.c_str());
return 1;
}
std::stringstream text;
text << file.rdbuf();
std::string key = text.str();
while (!key.empty() && (key.back() == '\n' || key.back() == '\r')) key.pop_back();
int status = 0;
for (int i = 0; i < count; i += 1) {
const std::string value = hmac(algorithm, key, paths[i]);
if (value.empty()) status = 1;
else std::printf("%s %s\n", value.c_str(), paths[i]);
}
return status;
}
 
} // namespace
 
int main(int argc, char** argv) {
const std::string command = argc > 1 ? argv[1] : "";
if (command == "digest" && argc >= 4) return digestFiles(argv[2], argc - 3, argv + 3);
if (command == "check" && argc == 3) return check(argv[2]);
if (command == "hmac" && argc >= 5) return hmacFiles(argv[2], argv[3], argc - 4, argv + 4);
if (command == "version") {
std::printf("%s\n", OpenSSL_version(OPENSSL_VERSION));
return 0;
}
std::fprintf(stderr,
"usage: openssl-tool digest <algorithm> <file>...\n"
" openssl-tool check <list>\n"
" openssl-tool hmac <algorithm> <key file> <file>...\n"
" openssl-tool version\n");
return 2;
}
shell
npx crossbind build -p wasi -e wasi -b release
wasmtime run --dir=. .crossbind/build/openssl-tool-wasi-wasm32-st-release.wasm digest sha256 notes.txt app.js
wasmtime run --dir=. .crossbind/build/openssl-tool-wasi-wasm32-st-release.wasm digest sha3-256 notes.txt
wasmtime run --dir=. .crossbind/build/openssl-tool-wasi-wasm32-st-release.wasm check SHA256SUMS
wasmtime run --dir=. .crossbind/build/openssl-tool-wasi-wasm32-st-release.wasm hmac sha256 webhook.key payload.json
output
9e5005fcfe4de0d34b99f2b92e9006fa8364fff8ed5ad5721f86fd06806bcba3 notes.txt
3faf44f0f523a12d45a05096b622c799f1bcedc6c4ad53e3cefa6b86e2f7a117 app.js
52c0b587e1ceeac3e286ca4c3bd36f719e4c7a299274fa567d1beb10d9d7e79f notes.txt
notes.txt: OK
app.js: OK
c64c37be918e54b40b5a114f9d11e2578b58adfc9fd624a1d06a6f5140e539bf payload.json
Digite para pesquisar em todas as páginas e seções do guia.
↑↓ navegar↵ abriresc fechar