crossbind
GitHub
← 所有库

OpenSSL

TLS 与密码学原语。

安装

在浏览器中运行;Node.js 和边缘运行环境也使用同一个包。构建目标:wasm32,单线程和多线程。

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();

crossbind 本身随你的打包工具插件一起提供;打包工具插件介绍了 Vite、Webpack、Rspack、Rsbuild、Rollup、esbuild、Bun 和 Next.js 的用法。

在浏览器中运行 OpenSSL 4:处理 WebCrypto 不支持的证书、TLS 和 .p12 文件

WebCrypto 能计算哈希、签名和加密,但它不能读取证书,不能打开 .p12 文件,也不支持 TLS。这些应用运行由 crossbind 编译的 OpenSSL 4.1.1 本身:它们能生成密钥和证书(包括后量子的 ML-DSA 密钥和证书),在标签页中的两个 OpenSSL 端点之间,使用 OpenSSL 默认的混合 ML-KEM 密钥交换和 Encrypted Client Hello 完成 TLS 1.3 握手,还能打开 .p12 文件,包括旧式的 RC2-40 文件。OpenSSL 采用 Apache-2.0 许可证。 首次运行时会下载一次 4.2 MB 的 WebAssembly;本页的所有应用都共用它,而且不会上传任何内容。

应用 01

生成密钥和证书,或读取任意 PEM

生成一个 RSA、ECDSA、Ed25519 或后量子 ML-DSA 密钥,再为它生成自签名证书或证书签名请求,然后像 openssl x509 -text 那样读回 OpenSSL 写出的内容。也可以粘贴证书、证书链、请求或密钥来检查它。WebCrypto 能生成密钥,但不能读取证书:这里是 OpenSSL 本身在标签页中运行,私钥绝不会被发送到任何地方。

RSA 密钥耗时最长:寻找它们的素数是一项随机的工作。ML-DSA-65 是 FIPS 204 中的后量子签名算法;它的证书仅供实验使用。

运行 OpenSSL 4.1.1(采用 Apache-2.0 许可证): 源代码 · 许可证 · 构建配方
生成密钥和证书,或者检查示例证书链。
查看代码
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
应用 02

在此标签页中,两个 OpenSSL 端点之间的 TLS 握手

一个 OpenSSL 4 客户端和服务器通过内存缓冲区进行握手,由这个页面在两者之间传递每一个字节,并列出每一条消息。你可以看到 OpenSSL 默认选择的混合后量子密钥交换,用 Encrypted Client Hello 隐藏服务器名称,或者翻转线路上的一个比特,看着客户端拒绝它。网页无法自行建立 TLS 连接,所以两端都在这里运行;这个页面自己的 HTTPS 用的是浏览器的 TLS,而不是 OpenSSL 的。

服务器的证书由客户端信任的 CA 为 secret.example 和 public.example 颁发,这些都在每种密钥类型首次运行时于模块中生成。RSA 密钥需要几秒钟。

运行 OpenSSL 4.1.1(采用 Apache-2.0 许可证): 源代码 · 许可证 · 构建配方
进行握手,查看握手的每一条消息,以及线路上的观察者能看到什么。
查看代码
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
应用 03

打开 .p12 或 .pfx 文件,也可以新建一个

选择一个 .p12 或 .pfx 文件并输入它的密码:密钥、证书和证书链会以 PEM 格式输出,同时给出保护每个部分的加密算法和 MAC,名称与 openssl pkcs12 -info 给出的相同。OpenSSL 1.1.1 和其他旧工具写出的文件使用 RC2-40 和 3DES,OpenSSL 3 及更高版本把它们放在 legacy provider 中;这个构建附带了它,并且只在处理这类文件时才加载。文件在这个标签页中读取,不会上传。

未选择文件

示例在模块中生成:一个 P-256 密钥和一张 sample.example 的自签名证书,像 openssl pkcs12 -export 那样用密码“sample”打包,可以带或不带 -legacy。

运行 OpenSSL 4.1.1(采用 Apache-2.0 许可证): 源代码 · 许可证 · 构建配方
打开 .p12 或 .pfx 文件,或者试试示例,看看其中有什么。
查看代码
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

示例

每个示例都由一个小小的 C++ 头文件和调用它的 JavaScript 组成,并附有构建本站时它输出的内容。仅 JavaScript 标签页直接使用 OpenSSL 自己的头文件完成同样的事,不需要 C++ 文件。最后一个是为 WASI 构建的完整 C++ 程序。

像 openssl x509 -text 那样读取证书

在 C++ 中完成人们打开证书时想做的事:PEM_read_bio_X509 解析证书,X509_NAME_print_ex 输出主题和颁发者,ASN1_TIME_print_ex 输出有效期,X509V3_EXT_print 输出备用名称,X509_check_host 像 TLS 客户端那样匹配主机名,X509_digest 计算 SHA-256 指纹。WebCrypto 没有 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());
输出首次运行需下载 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

哈希与 HMAC

EVP_Q_digest 可以按名称选用任意摘要算法,对已在内存中的数据计算哈希;EVP_DigestUpdate 可以在文件或下载内容陆续到达时分段接收数据;EVP_Q_mac 则生成 webhook 和 API 请求签名所用的 HMAC。WebCrypto 只支持到 SHA-1 和 SHA-2;这里的 SHA-3 和 BLAKE2 来自 OpenSSL。每一行都是相应标准公布的测试向量。

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());
输出首次运行需下载 4.2 MB
SHA256 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
SHA3-256 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
BLAKE2B-512 ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923
HMAC-SHA256 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
streamed SHA256 cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0

用 AES-256-GCM 加密并认证

使用 AES-256-GCM 的 EVP_CipherInit_ex2 可以一次完成加密和认证;EVP_CTRL_AEAD_GET_TAG 读取 16 字节的标签,设置 EVP_CTRL_AEAD_SET_TAG 后,解密会拒绝任何被改动过的内容,包括以明文传输的关联数据。输出是密文加标签,正是 WebCrypto 读取的格式。

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);
}
输出首次运行需下载 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

生成密钥、签名并验证

EVP_PKEY_Q_keygen 生成密钥对,PEM_write_bio_PUBKEY 导出其中的公钥部分,EVP_DigestSign 进行签名,EVP_DigestVerify 只凭那份 PEM 就能完成验证。同样的调用可以用 ECDSA P-256、Ed25519 和 ML-DSA-65(FIPS 204 中的后量子签名算法)进行签名。密钥是随机的,所以示例输出的是不变的部分:大小、强度和验证结果。

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}`);
}
输出首次运行需下载 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

为 localhost 生成自签名证书

用 C++ 回答关于 OpenSSL 被问得最多的问题:X509_new、一个随机序列号、用于浏览器匹配的 subjectAltName 的 X509V3_EXT_conf_nid,以及用它所认证的密钥调用 X509_sign,这些正是 openssl req -x509 -addext subjectAltName=... 写入的字段。密钥来自签名示例,证书示例会读回结果。

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));
输出首次运行需下载 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

基于 OpenSSL 的校验和工具

WASI 没有 JavaScript 绑定:程序就是一个链接了 OpenSSL 的 main(),构建成一个 .wasm,再用 wasmtime 运行。这个程序可以使用 OpenSSL 支持的任意摘要算法,以 sha256sum 的格式输出文件摘要;像 sha256sum -c 那样检查校验和列表;还能计算 webhook 发送方为其载荷签名所用的 HMAC。

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
输入关键词,搜索指南的所有页面和章节。
↑↓ 选择↵ 打开esc 关闭