Dart X509Certificate
last modified November 14, 2026
The X509Certificate class from the dart:io library
represents an X.509 certificate, the kind of certificate a server presents
during a TLS handshake. In this article we read certificates from secure
connections, look at their encodings, check their expiry, and decide what to
do with certificates that are not trusted.
The examples were run with Dart 3.13.
Basic definition
An X509Certificate object gives read-only access to the main
fields of a certificate:
subject– the distinguished name of the certificate owner,issuer– the distinguished name of the authority that signed it,startValidityandendValidity– the validity period asDateTimevalues,pem– the certificate as PEM text,der– the certificate as raw DER bytes,sha1– the SHA-1 fingerprint of the DER bytes.
The class has no public constructor and cannot parse a certificate file.
We get instances from the TLS layer: from
SecureSocket.peerCertificate, from
HttpClientResponse.certificate, or as the argument of an
onBadCertificate callback. The verification itself is done by
the TLS implementation; the class only describes the certificate.
Inspecting a server certificate
The first example connects to a web server and prints the main fields of its certificate.
import 'dart:io';
void main() async {
final socket = await SecureSocket.connect('example.com', 443);
final cert = socket.peerCertificate;
socket.destroy();
if (cert == null) {
print('No certificate');
return;
}
print('Subject: ${cert.subject}');
print('Issuer: ${cert.issuer}');
print('Valid from: ${cert.startValidity.toUtc()}');
print('Valid to: ${cert.endValidity.toUtc()}');
}
SecureSocket.connect opens a TCP connection and performs the
TLS handshake. When it completes, the peerCertificate property
holds the certificate the server presented. It is nullable, because a peer
does not have to send one; servers always do, but clients usually don't.
socket.destroy();
We need only the certificate, so we tear down the connection with
destroy. The close method would wait for the server
to close its side of the connection, and the program would hang.
The subject and issuer are distinguished names in the slash-separated OpenSSL format. The validity dates are printed in UTC.
$ dart run inspect.dart Subject: /CN=example.com Issuer: /C=US/O=SSL Corporation/CN=Cloudflare TLS Issuing ECC CA 3 Valid from: 2026-09-26 22:49:11.000Z Valid to: 2026-12-25 22:56:35.000Z
PEM, DER and the fingerprint
A certificate is a binary DER structure. PEM is the same data encoded in Base64 and wrapped in header and footer lines. This example prints both encodings and shows that they hold the same bytes.
import 'dart:convert';
import 'dart:io';
String hex(List<int> bytes) => bytes
.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase())
.join(':');
void main() async {
final socket = await SecureSocket.connect('example.com', 443);
final cert = socket.peerCertificate!;
socket.destroy();
final lines = cert.pem.trim().split('\n');
print('PEM: ${lines.length} lines');
print(lines.first);
print('${lines[1].substring(0, 40)}...');
print(lines.last);
print('DER: ${cert.der.length} bytes');
final body = lines.sublist(1, lines.length - 1).join();
final decoded = base64.decode(body);
print('PEM body equals DER: ${_equal(decoded, cert.der)}');
print('SHA-1: ${hex(cert.sha1)}');
}
bool _equal(List<int> a, List<int> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
The pem property returns the text form. We print only its first
lines, because a certificate takes over twenty lines of Base64.
final body = lines.sublist(1, lines.length - 1).join(); final decoded = base64.decode(body);
We drop the BEGIN and END lines, join the rest and
decode it from Base64. The result is identical to the bytes from the
der property.
String hex(List<int> bytes) => bytes
.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase())
.join(':');
The sha1 property is a list of 20 bytes. The hex
function formats it the way openssl and browsers show
fingerprints. A fingerprint identifies one exact certificate; any change in
the certificate produces a different value.
$ dart run encodings.dart PEM: 23 lines -----BEGIN CERTIFICATE----- MIID5jCCA42gAwIBAgIQAe7mqrtSHV4U/DFf2ZhW... -----END CERTIFICATE----- DER: 1002 bytes PEM body equals DER: true SHA-1: 89:9C:B2:59:E7:DE:8D:F1:00:33:A2:AF:48:C2:2C:2F:65:80:A2:1D
Checking the expiry date
An HTTPS response also carries the server certificate. This example uses it to warn about a certificate that expires soon.
import 'dart:io';
void main() async {
final client = HttpClient();
try {
final request = await client.getUrl(Uri.parse('https://example.com/'));
final response = await request.close();
await response.drain<void>();
final cert = response.certificate;
if (cert == null) {
print('No certificate');
return;
}
final daysLeft = cert.endValidity.difference(DateTime.now()).inDays;
print('Status: ${response.statusCode}');
print('Subject: ${cert.subject}');
print('Expires: ${cert.endValidity.toUtc()}');
print(daysLeft < 30
? 'Warning: the certificate expires in $daysLeft days'
: 'The certificate is valid for another $daysLeft days');
} finally {
client.close();
}
}
After the request completes, the certificate property of the
HttpClientResponse holds the server certificate. We drain the
response body because we don't need it.
final daysLeft = cert.endValidity.difference(DateTime.now()).inDays;
The difference between the end of validity and the current time tells us how many days the certificate has left. Monitoring tools check this value regularly and alert before the certificate expires.
The number of days in the output depends on the day you run the example and on the certificate the server currently uses.
$ dart run https_client.dart Status: 200 Subject: /CN=example.com Expires: 2026-12-25 22:56:35.000Z The certificate is valid for another 41 days
Creating a self-signed certificate
The next two examples run a local TLS server. It needs a certificate and a
private key, which we create with openssl.
$ openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem \
-days 365 -subj "/CN=localhost/O=ZetCode Demo" \
-addext "subjectAltName=DNS:localhost"
$ openssl x509 -in cert.pem -noout -subject -issuer -dates -fingerprint -sha1
subject=CN = localhost, O = ZetCode Demo
issuer=CN = localhost, O = ZetCode Demo
notBefore=Nov 14 20:57:03 2026 GMT
notAfter=Nov 14 20:57:03 2027 GMT
sha1 Fingerprint=8D:C6:2E:27:AA:0E:DC:D0:A8:6A:A2:95:8B:BA:83:62:28:85:5D:03
Handling an untrusted certificate
A self-signed certificate is not issued by any trusted authority, so TLS
clients reject it. The onBadCertificate callback lets us
inspect such a certificate and decide whether to accept it.
import 'dart:convert';
import 'dart:io';
const pinnedSha1 = '8D:C6:2E:27:AA:0E:DC:D0:A8:6A:A2:95:8B:BA:83:62:28:85:5D:03';
String hex(List<int> bytes) => bytes
.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase())
.join(':');
void main() async {
final serverContext = SecurityContext()
..useCertificateChain('cert.pem')
..usePrivateKey('key.pem');
final server = await SecureServerSocket.bind('localhost', 4433, serverContext);
server.listen(
(client) {
client.write('Hello from the TLS server');
client.close();
client.drain<void>();
},
onError: (Object e) {},
);
try {
await SecureSocket.connect('localhost', 4433);
} on HandshakeException catch (e) {
print('Without a callback: ${e.osError?.message.trim()}');
}
final socket = await SecureSocket.connect(
'localhost',
4433,
onBadCertificate: (X509Certificate cert) {
final fingerprint = hex(cert.sha1);
print('Untrusted certificate: ${cert.subject}');
print('Fingerprint: $fingerprint');
return fingerprint == pinnedSha1;
},
);
print('Received: ${await utf8.decodeStream(socket)}');
socket.destroy();
await server.close();
}
The program starts a SecureServerSocket on port 4433 with the
generated certificate and key. Each client gets a greeting.
onError: (Object e) {},
A client that rejects the certificate aborts the handshake, and the server socket reports that as an error event. We ignore it so that the server keeps accepting connections.
try {
await SecureSocket.connect('localhost', 4433);
} on HandshakeException catch (e) {
print('Without a callback: ${e.osError?.message.trim()}');
}
The first connection uses the default settings. The certificate cannot be
verified, so the connection fails with a HandshakeException.
onBadCertificate: (X509Certificate cert) {
final fingerprint = hex(cert.sha1);
...
return fingerprint == pinnedSha1;
},
The second connection supplies the callback. It receives the rejected
certificate; returning true accepts it and the handshake
continues. We accept the certificate only if its SHA-1 fingerprint equals
the one we know, which is called certificate pinning. Never return
true unconditionally: that accepts any certificate and removes
the protection TLS gives against man-in-the-middle attacks.
The pinnedSha1 constant holds the fingerprint printed by the
openssl command above. Your certificate has a different
fingerprint, so replace the value before running the example.
$ dart run self_signed.dart Without a callback: CERTIFICATE_VERIFY_FAILED: self signed certificate(handshake.cc:320) Untrusted certificate: /CN=localhost/O=ZetCode Demo Fingerprint: 8D:C6:2E:27:AA:0E:DC:D0:A8:6A:A2:95:8B:BA:83:62:28:85:5D:03 Received: Hello from the TLS server
Trusting a certificate with SecurityContext
Instead of overriding verification in a callback, we can tell the client which certificates to trust. Verification then succeeds normally.
import 'dart:convert';
import 'dart:io';
void main() async {
final serverContext = SecurityContext()
..useCertificateChain('cert.pem')
..usePrivateKey('key.pem');
final server = await SecureServerSocket.bind('localhost', 4433, serverContext);
server.listen(
(client) {
client.write('Hello from the TLS server');
client.close();
client.drain<void>();
},
onError: (Object e) {},
);
final clientContext = SecurityContext(withTrustedRoots: false)
..setTrustedCertificates('cert.pem');
final socket = await SecureSocket.connect(
'localhost',
4433,
context: clientContext,
);
final cert = socket.peerCertificate!;
print('Trusted certificate: ${cert.subject}');
print('Issued by itself: ${cert.subject == cert.issuer}');
print('Received: ${await utf8.decodeStream(socket)}');
socket.destroy();
await server.close();
}
The server is the same as in the previous example. The client creates its
own SecurityContext.
final clientContext = SecurityContext(withTrustedRoots: false)
..setTrustedCertificates('cert.pem');
With withTrustedRoots: false the context starts without the
system's certificate authorities, and setTrustedCertificates
adds our certificate as the only trusted one. The client therefore accepts
our local server and nothing else.
A self-signed certificate has the same subject and issuer, which the program confirms.
$ dart run trusted_context.dart Trusted certificate: /CN=localhost/O=ZetCode Demo Issued by itself: true Received: Hello from the TLS server
Source
Dart API: X509Certificate class
Dart API: SecureSocket class
Dart API: SecurityContext class
X509Certificate describes the certificate a peer presents during
the TLS handshake. We get it from a secure socket, an HTTPS response or the
onBadCertificate callback, and use it to show certificate details,
monitor expiry and pin certificates. See also the
SecureSocket,
SecurityContext and
HttpClient tutorials.
Author
List all Dart tutorials.