dvPublicKeyFromCertificate function
Extracts the RSA public key from a base64 DER X.509 certificate.
Implementation
RSAPublicKey dvPublicKeyFromCertificate(String base64Der) {
final Uint8List der =
base64.decode(base64Der.replaceAll(RegExp(r'\s|-----[^-]+-----'), ''));
final ASN1Parser parser = ASN1Parser(der);
final ASN1Sequence certificate = parser.nextObject() as ASN1Sequence;
final ASN1Sequence tbs = certificate.elements!.first as ASN1Sequence;
// SubjectPublicKeyInfo is the first element that is itself a sequence
// containing an algorithm identifier and a bit string. Located by shape
// rather than by index, because the optional version field shifts every
// index after it.
for (final ASN1Object element in tbs.elements!) {
if (element is! ASN1Sequence) continue;
final List<ASN1Object>? parts = element.elements;
if (parts == null || parts.length != 2) continue;
if (parts[0] is! ASN1Sequence || parts[1] is! ASN1BitString) continue;
final ASN1BitString bits = parts[1] as ASN1BitString;
final Uint8List keyBytes = Uint8List.fromList(bits.stringValues!);
final ASN1Sequence key =
ASN1Parser(keyBytes).nextObject() as ASN1Sequence;
return RSAPublicKey(
(key.elements![0] as ASN1Integer).integer!,
(key.elements![1] as ASN1Integer).integer!,
);
}
throw const FormatException(
'No SubjectPublicKeyInfo found in the certificate.',
);
}