openssl_bindings 1.0.0
openssl_bindings: ^1.0.0 copied to clipboard
FFI bindings to OpenSSL cryptographic library for Dart, providing native access to encryption, hashing, and SSL/TLS functionality.
OpenSSL Bindings for Dart #
Robust and idiomatic FFI bindings for OpenSSL 3.x in Dart. This library provides advanced cryptographic operations, X.509 certificate generation/parsing, and secure networking (TLS/DTLS) directly via Dart FFI, without requiring native compilation steps (beyond having OpenSSL installed/available).
It focuses on memory safety (automatic resource management), flexibility (customizable DLL paths), and providing a clean object-oriented API.
Core Features #
Infrastructure & Security #
- Flexible Loading: Load
libcryptoandlibsslfrom system paths, environment variables, or explicit paths defined at runtime (ideal for bundled apps). - Memory Safety: Automatic memory management for native structures using Dart's
Finalizerto prevent leaks. - CI Tested: Verified across Windows and Linux environments.
X.509 & PKI #
- Complete Parsing: Read Version, Serial, Validity (
notBefore,notAfter), Subject, and Issuer. - Large Serial Support (ASN.1/BN):
x509GetSerialBytes,x509GetSerialHex,x509GetSerialDecimal.asn1IntegerToHex,asn1IntegerToDecimal,asn1IntegerFromHex.- Fluent Builders:
X509CertificateBuilder: Create Self-Signed or CA-Signed certificates.X509RequestBuilder: Generate CSRs (Certificate Signing Requests).
X509CrlBuilder: Generate and sign CRLs directly via FFI.- Formats: Full support for PEM and DER.
Cryptography & Signing (CMS/PAdES) #
- Key Management: Generate and load RSA/EVP keys (PEM/DER/Encrypted PEM).
- Modern/PQC Key Generation:
- EdDSA/XDH:
generateEd25519,generateEd448,generateX25519,generateX448. - ML-DSA:
generateMlDsa44,generateMlDsa65,generateMlDsa87. - Generic provider keygen:
generateKeyByName(...).
- EdDSA/XDH:
- Symmetric Ciphers:
- AES-128/256 (CBC and GCM).
- ChaCha20 and ChaCha20-Poly1305.
- Rijndael aliases (mapped to AES-128/256 CBC and GCM).
- PKCS#7 helpers:
pkcs7Pad,pkcs7Unpad,aesCbcPkcs7Encrypt,aesCbcPkcs7Decrypt. - CMS/PKCS#7:
- Detached Signatures: Critical for PAdES/CAdES standards.
- External Digest Signing: Support for signing pre-calculated hashes (e.g., for Hardware Security Modules or remote signing flows).
- Verification: Verify CMS signatures against Trusted Root stores.
- One-shot Signatures:
signOneShot/verifyOneShot.- ML-DSA helpers:
signMlDsa/verifyMlDsa.
Secure Networking (TLS & DTLS) #
- Async TLS:
SecureSocketOpenSslAsync(API compatible withdart:ioSocket). - Sync TLS:
SecureSocketOpenSslSync(Blocking API, useful for tunnels/proxies). - DTLS 1.2+: Full support for
DtlsClientandDtlsServerover UDP.
CRL & OCSP (New) #
X509CrlandX509CrlBuilder: Generate and sign CRLs without invoking the OpenSSL executable.OcspResponseBuilderandOcspMixin: Build DER OCSP responses via FFI.PkiMixincache helpers:getCachedCrl/putCachedCrlandgetCachedOcsp/putCachedOcsp(TTL-based).
Issuer Matching & Truststore Performance #
- Issuer Matching Helpers:
extractAkiSki,issuerSerialKey,certMatchesIssuer,prefilterIssuerCandidates.- Follows secure behavior: binary hints only, no CN/text decision, fallback to full set on ambiguity.
- Truststore / Parse Caches:
getOrCreateStore(storeKey, rootsDer)forX509_STOREpooling.getOrCreateParsedX509(der)for parsedX509*cache by DER fingerprint.fingerprintSha256(...)for stable cache keys.- PEM/DER chain utilities:
loadCertificatesFromPemChain,convertPemChainToDerList.convertCertificatePemToDer,convertCertificateDerToPem.
Legacy PKCS#12 (RC2/RC4) on OpenSSL 3.x #
ProviderMixin:loadLegacyProvider(),loadProvider(name),isProviderAvailable(name),setProviderSearchPath(dir).parsePkcs12(..., legacy: true)andautoLegacy: true(detects, loads and, when the module is missing, uses the pure Dart decoder).pkcs12LegacyAlgorithms(der)/pkcs12NeedsLegacyProvider(der): identify the algorithm by OID without opening the file.decodePkcs12Pure(...)/parsePkcs12Pure(...): 100% Dart PKCS#12, no FFI and no provider.
X.509 chain verification (New) #
verifyChain(...)on top ofX509_verify_cert, with CRLs, verification time and partial chains.VerificationResult: OpenSSL error code, message, depth, failing certificate and the chain that was built.verifyCertificateSignature(cert, issuer).
Time-stamping (RFC 3161) (New) #
buildTimestampRequest/createTimestampResponse/verifyTimestamp: request, issue and verify tokens.- Runs an internal TSA with a caller-supplied serial, policy and accuracy; verification covers signature, imprint, nonce, policy and chain.
Argon2 (RFC 9106) #
argon2HashPassword/argon2VerifyPasswordwith PHC strings, andargon2Derivefor raw key derivation.- Native backend through OpenSSL's
EVP_KDF(3.2+) with a pure Dart fallback;hasNativeArgon2tells which is in use.
WebAuthn / passkeys #
sign/verifyroute Ed25519, Ed448 and ML-DSA keys to the one-shot API automatically.loadPublicKeyDer/loadPublicKeyBytesfor SubjectPublicKeyInfo coming from COSE keys.
ICP-Brasil #
IcpBrasilParser: CPF/CNPJ using the official DOC-ICP-04 offsets, with check-digit validation.- Reads the rest of the positional block (birth date, NIS, ID card) and every ICP-Brasil
otherNameOID. maskCpf/maskCnpjfor log lines, and anIcpBrasilInfo.toString()that never prints a document number.
TLS (Recommended suites) #
- Recommended TLS 1.2 cipher suite list and TLS 1.3 ciphersuite list (with TLS 1.3 IDs).
Installation #
Add to your pubspec.yaml:
dependencies:
openssl_bindings: any
Requirements #
- Dart SDK: 3.0+
- OpenSSL: Version 3.0 or higher.
- Windows: Recommended Win64OpenSSL.
- Linux:
sudo apt-get install libssl-dev(or equivalent).
Coverage (CI + local) #
- CI: The workflow
.github/workflows/dart.ymlrunsdart test --coverage=coverage, converts tocoverage/lcov.info, uploads it as artifact, and sends it to Codecov. - Local:
dart test --coverage=coverage
dart pub global activate coverage
format_coverage --lcov --in=coverage --out=coverage/lcov.info --report-on=lib --packages=.dart_tool/package_config.json
- To show the badge in GitHub, keep the Codecov badge above and configure
CODECOV_TOKENin repository secrets (for private repos; public repos may not require token).
Usage Examples #
1. Initialization and Custom Paths #
The OpenSSL class is the main entry point. You can let it find the library automatically or inject specific paths.
import 'package:openssl_bindings/openssl.dart';
// 1. Standard usage (uses PATH or env vars)
final openssl = OpenSSL();
// 2. Custom usage (e.g., bundling binaries with your app)
final opensslCustom = OpenSSL(
cryptoPath: r'./libs/libcrypto-3-x64.dll',
sslPath: r'./libs/libssl-3-x64.dll',
);
2. Generating Certificates (X509 Builder) #
Easily create RSA keys and self-signed certificates.
import 'package:openssl_bindings/openssl.dart';
// Generate RSA Key
final key = openssl.generateRsa(2048);
// Configure the Certificate
final builder = X509CertificateBuilder(openssl)
..setSerialNumber(1001)
..setValidity(notBeforeOffset: 0, notAfterOffset: 31536000) // 1 year
..setSubject(commonName: 'My App Root CA', country: 'US')
..setIssuerAsSubject() // Self-signed
..setPublicKey(key);
// Sign and export
final cert = builder.sign(key, hashAlgorithm: 'SHA256');
print(cert.toPem());
print(key.toPrivateKeyPem());
3. CMS/PAdES Signing (Detached) #
Create digital signatures for documents (like PDF/PAdES) where the signature is separate from the content.
import 'package:openssl_bindings/openssl.dart';
final signer = CmsPkcs7Signer(openssl);
// Detached Signature (CMS contains only the signature, not the file content)
final signatureDer = signer.signDetached(
content: fileBytes,
certificateDer: myCertBytes,
privateKey: myPrivateKey,
);
// Verify
final isValid = openssl.verifyCmsDetached(
cmsDer: signatureDer,
content: fileBytes,
trustedCertDer: rootCaBytes,
);
4. Secure Networking (DTLS Client) #
Example of a DTLS client connecting to a server, using custom library paths.
import 'package:openssl_bindings/openssl.dart';
void main() async {
// Initialize DTLS with custom OpenSSL paths
final client = DtlsClient(
cryptoPath: r'./libs/libcrypto.so',
sslPath: r'./libs/libssl.so',
);
final connection = await client.connect(
InternetAddress('127.0.0.1'),
4433,
pskIdentity: 'user',
pskKey: 'password', // Or use certificates
);
print('Connected via DTLS!');
connection.listen((data) {
print('Received: ${String.fromCharCodes(data)}');
});
connection.send(Uint8List.fromList('Hello DTLS'.codeUnits));
}
5. Async TLS Client (TCP) #
import 'package:openssl_bindings/openssl.dart';
final socket = await SecureSocketOpenSslAsync.connect('example.com', 443);
await socket.send(utf8.encode('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n'));
socket.listen((data) {
print(utf8.decode(data));
});
6. Serial Number APIs (ASN.1 / BN) #
import 'package:openssl_bindings/openssl.dart';
final cert = openssl.loadCertificatePem(pem);
final serialBytes = openssl.x509GetSerialBytes(cert.handle);
final serialHex = openssl.x509GetSerialHex(cert.handle); // e.g. 0x01ab...
final serialDec = openssl.x509GetSerialDecimal(cert.handle);
print(serialBytes.length);
print(serialHex);
print(serialDec);
7. Legacy PKCS#12 (40-bit RC2) #
final openssl = OpenSSL();
final der = File('certificate.p12').readAsBytesSync();
// Diagnosis without opening the file
if (openssl.pkcs12NeedsLegacyProvider(der)) {
print(openssl.pkcs12LegacyAlgorithms(der)); // [pbeWithSHA1And40BitRC2-CBC]
}
// Recommended: sorts itself out (legacy provider or pure Dart decoder)
final bundle = openssl.parsePkcs12(der, password: pass, autoLegacy: true);
// Explicit control
openssl.loadLegacyProvider();
final withProvider = openssl.parsePkcs12(der, password: pass, legacy: true);
// 100% Dart, no FFI and no legacy module installed
final pure = decodePkcs12Pure(der, password: pass);
print(pure.certificatePem);
print(pure.privateKeyPem);
8. X.509 chain verification #
final result = openssl.verifyChain(
certificate: receivedCertificate,
anchors: [rootCa],
intermediates: [intermediateCa],
crls: [caCrl],
checkRevocation: true,
verificationTime: signatureDate, // validate as of signing time
);
if (!result.valid) {
print('${result.message} (code ${result.errorCode}, depth ${result.depth})');
print('failed at: ${result.failingCertificate}');
}
result.dispose();
9. Argon2 password hashing #
final openssl = OpenSSL();
// Uses OpenSSL's native Argon2 when the loaded libcrypto is 3.2+,
// and the vendored pure Dart implementation otherwise.
final phc = openssl.argon2HashPassword('user-password');
// $argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>
final ok = openssl.argon2VerifyPassword(phc, 'user-password');
// Raw derivation, for key material rather than password storage
final key = openssl.argon2DeriveFromString(
'passphrase',
openssl.randomBytes(16),
options: const Argon2Options(memoryKib: 65536, iterations: 3, length: 32),
);
10. WebAuthn / passkey keys #
// A COSE public key re-encoded as SubjectPublicKeyInfo
final publicKey = openssl.loadPublicKeyDer(spkiDer);
// ES256 (P-256), EdDSA (Ed25519) and RS256 all go through the same call:
// Ed25519 rejects an external digest, so sign/verify switch to the one-shot
// API on their own.
final valid = openssl.verify(publicKey, signedData, signature);
11. Time-stamping (RFC 3161) #
// Client: ask a TSA to stamp the hash of a signature
final request = openssl.buildTimestampRequest(hash: signatureHash);
final answer = await postToTsa(request.der); // application/timestamp-query
final check = openssl.verifyTimestamp(
responseDer: answer,
hash: signatureHash,
nonce: request.nonce, // matching it is what rules out a replay
anchors: [tsaRootCa],
);
print(check.token?.genTime);
// Internal TSA: sign with a certificate carrying
// extendedKeyUsage = critical, timeStamping
final response = openssl.createTimestampResponse(
requestDer: incomingRequest,
signerCertificate: tsaCertificate,
signerKey: tsaKey,
defaultPolicyOid: '1.3.6.1.4.1.99999.1.1',
serialNumber: nextSerialFromTheDatabase, // must be unique per TSA
);
// Later, with only the archived token and no request left
final archived = openssl.verifyTimestamp(
tokenDer: token.der,
hash: signatureHash,
anchors: [tsaRootCa],
);
12. Issuer pre-filter + secure fallback #
final childInfo = openssl.extractAkiSki(childCertPtr);
final candidates = openssl.prefilterIssuerCandidates<Pointer<X509>>(
candidates: allIssuerCandidates,
matches: (issuerPtr) {
final issuerInfo = openssl.extractAkiSki(issuerPtr);
return openssl.certMatchesIssuer(
childAki: childInfo.aki,
issuerSki: issuerInfo.ski,
issuerSerialBytes: issuerInfo.serialBytes,
issuerNameHash: issuerInfo.issuerNameHash,
);
},
);
// Always run full certificate chain validation afterwards.