parsePkcs12 method
Parses PKCS#12/PFX (DER) and returns key, certificate and chain.
legacy loads the OpenSSL 3.x legacy provider before calling
PKCS12_parse. It is needed for files encrypted with algorithms that
left the default provider in 3.0, typically
pbeWithSHA1And40BitRC2-CBC and pbeWithSHA1And128BitRC4. Without the
provider, OpenSSL fails with a generic error that looks like a wrong
password.
Use pkcs12NeedsLegacyProvider to decide beforehand, or just pass
legacy: true — loading the provider is idempotent and keeps the
default provider active.
autoLegacy handles everything on its own: it detects the algorithm by
OID, loads the provider when the file needs it and, if the legacy
module is not installed, opens the file with the pure Dart decoder
(parsePkcs12Pure). This is the option to reach for in application code.
Implementation
Pkcs12Bundle parsePkcs12(
Uint8List der, {
String password = '',
bool legacy = false,
bool autoLegacy = false,
}) {
final arena = Arena();
Pointer<PKCS12> p12 = nullptr;
if (legacy) {
_providerMixin.loadLegacyProvider();
} else if (autoLegacy && pkcs12NeedsLegacyProvider(der)) {
// With no `legacy` module installed, fall back to the pure Dart decoder
// instead of failing: the resulting bundle is the same.
final provider =
_providerMixin.loadLegacyProvider(required: false);
if (provider == null) {
return parsePkcs12Pure(der, password: password);
}
}
try {
final inPtr = arena<UnsignedChar>(der.length);
inPtr.cast<Uint8>().asTypedList(der.length).setAll(0, der);
final inOutPtr = arena<Pointer<UnsignedChar>>();
inOutPtr.value = inPtr;
p12 = bindings.d2i_PKCS12(nullptr, inOutPtr, der.length);
if (p12 == nullptr) {
throw OpenSslException('d2i_PKCS12 failed');
}
final pkeyPtr = calloc<Pointer<EVP_PKEY>>();
final certPtr = calloc<Pointer<X509>>();
final caPtr = calloc<Pointer<stack_st_X509>>();
Pointer<Char> passPtr = nullptr;
if (password.isNotEmpty) {
passPtr = password.toNativeUtf8(allocator: calloc).cast<Char>();
}
try {
final result = bindings.PKCS12_parse(
p12,
passPtr,
pkeyPtr,
certPtr,
caPtr,
);
if (result != 1) {
throw _pkcs12ParseException(der, usedLegacy: legacy);
}
final pkey = EvpPkey(pkeyPtr.value, this as OpenSSL);
final cert = X509Certificate(certPtr.value, this as OpenSSL);
final caStack = caPtr.value;
final ca = caStack == nullptr
? const <X509Certificate>[]
: _x509StackToList(
caStack.cast<OPENSSL_STACK>(),
duplicateCerts: false,
freeStackOnly: true,
);
return Pkcs12Bundle(
privateKey: pkey,
certificate: cert,
caCertificates: ca,
);
} finally {
calloc.free(pkeyPtr);
calloc.free(certPtr);
calloc.free(caPtr);
if (passPtr != nullptr) {
calloc.free(passPtr);
}
}
} finally {
if (p12 != nullptr) {
bindings.PKCS12_free(p12);
}
arena.releaseAll();
}
}