TLS and HTTPS
suggest changeTransport Layer Security (TLS) and HTTPS protect network communications from eavesdropping, tampering, and impersonation. In Dart, TLS support is built directly into dart:io via SecurityContext, SecureSocket, HttpClient, and HttpServer.bindSecure().
The SecurityContext Class
All TLS and HTTPS operations in dart:io rely on a SecurityContext. It stores trusted Certificate Authorities (CAs), client identity certificates, and private keys.
SecurityContext.defaultContext: Preloaded with the operating system's trusted root CA certificates.SecurityContext(): An empty security context where you explicitly define trusted certificates and keys.
Client-Side HTTPS Requests
Making standard HTTPS requests using package:http automatically verifies the server's TLS certificate chain against system root certificates:
import 'package:http/http.dart' as http;
void main() async {
// Automatically establishes TLS handshake with certificate verification
final response = await http.get(Uri.parse('https://api.github.com'));
print('HTTPS Status: ${response.statusCode}');
}
Custom CA Certificates (Self-Signed & Internal PKI)
When connecting to internal enterprise APIs or development servers with self-signed certificates, load your custom Root CA certificate into a custom SecurityContext:
import 'dart:io';
Future<void> fetchWithCustomCA() async {
final context = SecurityContext()
..setTrustedCertificates('path/to/enterprise-root-ca.pem');
final client = HttpClient(context: context);
try {
final request = await client.getUrl(Uri.parse('https://internal.corp.local/api'));
final response = await request.close();
print('Response status: ${response.statusCode}');
} finally {
client.close();
}
}
Certificate Pinning (Preventing MITM Attacks)
In high-security mobile applications (banking, healthcare), certificate pinning guards against compromised root CAs and malicious proxies by verifying the server's certificate fingerprint:
import 'dart:io';
import 'package:crypto/crypto.dart';
HttpClient createPinnedClient(String expectedSha256Fingerprint) {
// badCertificateCallback only runs when normal verification fails, so
// drop the trusted roots to make every certificate go through the pin check.
final client = HttpClient(context: SecurityContext(withTrustedRoots: false));
client.badCertificateCallback = (X509Certificate cert, String host, int port) {
// Compute SHA-256 hash of the DER-encoded server certificate
final certSha256 = sha256.convert(cert.der).toString().toUpperCase();
if (certSha256 == expectedSha256Fingerprint.toUpperCase()) {
return true; // Pin matched: trust certificate
}
stderr.writeln('SECURITY ALERT: Certificate pin mismatch for $host!');
return false; // Reject connection
};
return client;
}
Warning: Never use
client.badCertificateCallback = (cert, host, port) => true;in production. Disabling certificate verification exposes your users to trivial Man-In-The-Middle (MITM) attacks.
Mutual TLS (mTLS / Client Certificates)
Mutual TLS requires both the client and the server to authenticate each other using X.509 certificates:
import 'dart:io';
HttpClient createMtlsClient({
required String clientCertPath,
required String privateKeyPath,
required String caCertPath,
}) {
final context = SecurityContext(withTrustedRoots: false)
..setTrustedCertificates(caCertPath)
..useCertificateChain(clientCertPath)
..usePrivateKey(privateKeyPath);
return HttpClient(context: context);
}
Running an HTTPS Server in Dart
You can bind an HTTPS server directly using HttpServer.bindSecure or with package:shelf:
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
void main() async {
// Load SSL certificate and private key (e.g. from Let's Encrypt)
final securityContext = SecurityContext()
..useCertificateChain('certificates/fullchain.pem')
..usePrivateKey('certificates/privkey.pem');
final handler = const Pipeline()
.addMiddleware(logRequests())
.addHandler((Request request) => Response.ok('Secure response over HTTPS!\n'));
// Bind to port 8443 with TLS
final server = await io.serve(
handler,
InternetAddress.anyIPv4,
8443,
securityContext: securityContext,
);
print('HTTPS Server running securely on https://${server.address.host}:${server.port}');
}
Low-Level TLS Sockets with SecureSocket
For custom protocols (e.g. raw TCP, database drivers, SMTP over TLS), use SecureSocket:
import 'dart:convert';
import 'dart:io';
void main() async {
// Connect and perform TLS handshake
final socket = await SecureSocket.connect(
'example.com',
443,
supportedProtocols: ['http/1.1'],
);
print('Connected using: ${socket.selectedProtocol}');
// Send raw HTTP request over secure socket
socket.write('GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n');
await socket.flush();
socket.cast<List<int>>().transform(utf8.decoder).listen((data) {
stdout.write(data);
}, onDone: () => socket.destroy());
}
Best Practices
- Never bypass certificate verification: Do not disable certificate checks to "fix" local development certificate errors; install and trust the local CA certificate instead.
- Enforce TLS 1.2 or 1.3: Modern Dart runtimes disable legacy, insecure protocols (SSLv3, TLS 1.0, and TLS 1.1) by default.
- Protect private keys: Set restrictive file permissions (
chmod 600 privkey.pem) so only the application process owner can read TLS private keys. - Implement certificate pinning cautiously: Always provide backup pins and expiration plans to avoid bricking mobile apps when server certificates rotate.