smart_dev_pinning_plugin 2.7.0
smart_dev_pinning_plugin: ^2.7.0 copied to clipboard
This plugin creates a secure native TLS connection to execute HTTP requests with certificate pinning.
Smart Dev Pinning Plugin #
A high-performance Flutter plugin that provides secure native TLS connections for HTTP requests with advanced SSL certificate pinning capabilities. Supports both public key pinning and leaf certificate pinning with non-blocking asynchronous FFI implementation.
Features #
- 🔐 Dual Pinning Methods: SSL Certificate Pinning (Public Key & Leaf Certificate)
- 🚀 High Performance: Native FFI implementation with asynchronous execution.
- 🎯 Non-blocking UI: Isolate-based FFI execution prevents UI freezing on Android
- 📊 Built-in Benchmarking: Comprehensive performance analysis tools
- 🛡️ Type-safe API: Enum-based pinning method selection for enhanced safety
- 📱 Cross-platform: Full Android and iOS support
- ⚡ Zero Dependencies: Minimal external dependencies for maximum compatibility
Key Improvements #
- Asynchronous FFI: To execute FFI operations in separate Isolates
- Enhanced Performance: Non-blocking operations ensure responsive UI during network requests
- Consistent Behavior: Uniform asynchronous behavior across Android and iOS platforms
- Modern Architecture: Improved native integration with (Android) and Swift (iOS)
Requirements #
- Flutter 3.3.0 or higher
- Dart SDK 3.3.0 or higher
- Android API level 21+ (Android 5.0+)
- iOS 11.0+
Installation #
Add the dependency to your pubspec.yaml:
dependencies:
smart_dev_pinning_plugin: ^2.6.0
Then run:
flutter pub get
Usage Guide #
SSL Pinning Methods #
This plugin provides two robust certificate pinning strategies:
-
Public Key Pinning (
PinningMethod.publicKey):- Pins against the server's public key
- More resilient to certificate renewals
- Recommended for production environments
-
Leaf Certificate Pinning (
PinningMethod.certificate):- Pins against the complete leaf certificate
- Stricter security validation
- Requires certificate hash updates when certificates are renewed
Certificate Hash Generation #
Choose the appropriate method based on your pinning strategy:
Public Key Pinning Hash
Extract the public key hash for more flexible pinning:
# Extract public key hash (recommended for production)
openssl s_client -connect <HOST>:443 -servername <HOST> </dev/null 2>/dev/null \
| openssl x509 -pubkey -noout \
| openssl pkey -pubin -outform DER \
| openssl dgst -sha256 -binary \
| openssl base64
Certificate Pinning Hash
Extract the full certificate hash for strict validation:
# Extract leaf certificate hash
openssl s_client -connect <HOST>:443 -servername <HOST> 2>/dev/null \
| openssl x509 -outform DER \
| openssl dgst -sha256 -binary \
| openssl base64
Basic Implementation #
import 'package:smart_dev_pinning_plugin/smart_dev_pinning_plugin.dart';
final client = SecureClient();
// Public Key Pinning (Recommended)
try {
final response = await client.httpRequest(
certificateHash: "/UzJAZYxLBnEpBwXAcmd4WHi7f8aYgfMExGnoyp5B04=",
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts/1',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
pinningMethod: PinningMethod.publicKey,
);
print('Response: $response');
} catch (e) {
print('SSL Pinning failed: $e');
}
// Certificate Pinning
try {
final response = await client.httpRequest(
certificateHash: "YOUR_CERTIFICATE_HASH_HERE",
method: 'POST',
url: 'https://api.example.com/data',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
},
body: {'key': 'value'},
pinningMethod: PinningMethod.certificate,
);
print('Secure POST response: $response');
} catch (e) {
print('Certificate pinning error: $e');
}
Advanced Usage Examples #
Handling Different Request Types
final client = SecureClient();
// GET request with query parameters
final getResponse = await client.httpRequest(
certificateHash: "your_hash_here",
method: 'GET',
url: 'https://api.example.com/users?page=1&limit=10',
headers: {'Accept': 'application/json'},
pinningMethod: PinningMethod.publicKey,
);
// POST with JSON body
final postResponse = await client.httpRequest(
certificateHash: "your_hash_here",
method: 'POST',
url: 'https://api.example.com/users',
headers: {'Content-Type': 'application/json'},
body: {
'name': 'John Doe',
'email': '[email protected]'
},
pinningMethod: PinningMethod.publicKey,
);
// PUT with string body
final putResponse = await client.httpRequest(
certificateHash: "your_hash_here",
method: 'PUT',
url: 'https://api.example.com/users/123',
headers: {'Content-Type': 'text/plain'},
body: 'Updated user data',
pinningMethod: PinningMethod.publicKey,
);
Performance Benchmarking #
The plugin includes comprehensive benchmarking tools to analyze the performance impact of SSL pinning:
// The example app provides detailed performance analysis including:
// - Response time comparisons (Standard HTTP vs SSL Pinned requests)
// - Throughput measurements and statistical analysis
// - Visual performance metrics with charts and graphs
// - Memory usage and CPU impact assessment
// - Network latency analysis with SSL pinning overhead
Error Handling #
The plugin provides clear error handling for SSL pinning failures:
try {
final response = await client.httpRequest(
certificateHash: "invalid_hash",
method: 'GET',
url: 'https://example.com/api',
headers: {},
pinningMethod: PinningMethod.publicKey,
);
} on Exception catch (e) {
if (e.toString().contains('TLS Pinning Error')) {
// Handle certificate mismatch
print('Certificate pinning failed - possible MITM attack or expired certificate');
} else {
// Handle other network errors
print('Network error: $e');
}
}
Architecture Overview #
Android Implementation #
- Native Layer: Rust-based HTTP client with OpenSSL for TLS operations
- FFI Bridge: Asynchronous FFI calls using Flutter's
compute()function - Isolate Execution: Prevents UI blocking during network operations
iOS Implementation #
- Native Layer: Swift implementation using URLSession with custom certificate validation
- Method Channel: Direct communication between Dart and Swift code
- Background Queue: Network operations executed on background threads
API Reference #
SecureClient #
The main class for performing secure HTTP requests with certificate pinning.
Constructor
final client = SecureClient();
Creates a singleton instance of the secure HTTP client.
Methods
httpRequest()
Performs an HTTP request with SSL certificate pinning.
Future<String> httpRequest({
required String method,
required String url,
Object? body,
Map<String, String>? headers,
String? encoding,
required String certificateHash,
required PinningMethod pinningMethod,
})
Parameters:
| Parameter | Type | Description | Required |
|---|---|---|---|
method |
String |
HTTP method ('GET', 'POST', 'PUT', 'DELETE', etc.) | ✅ |
url |
String |
Target URL for the request | ✅ |
body |
Object? |
Request body (String, Map, or null) | ❌ |
headers |
Map<String, String>? |
HTTP headers as key-value pairs | ❌ |
encoding |
String? |
Character encoding (default: 'json') | ❌ |
certificateHash |
String |
Base64-encoded certificate or public key hash | ✅ |
pinningMethod |
PinningMethod |
Type of pinning validation to use | ✅ |
Returns: Future<String> - The HTTP response body
Throws:
ArgumentError- If body is not a String, Map, or nullException- If SSL pinning validation failsUnsupportedError- If platform is not supported
PinningMethod Enum #
Defines the certificate pinning validation strategy:
enum PinningMethod {
publicKey, // Pin against server's public key (recommended)
certificate, // Pin against complete leaf certificate
}
Extension Methods
extension PinningMethodExtension on PinningMethod {
String get value; // Returns string representation for native calls
}
Utility Functions #
parseResponse(String response)
Parses and validates HTTP responses for SSL pinning errors.
String parseResponse(String response)
Parameters:
response- Raw response string from native layer
Returns: Validated response string
Throws: Exception if response contains connection errors
Example Application #
The plugin includes a comprehensive example app demonstrating:
- Interactive SSL Pinning Testing: Real-time validation with multiple endpoints
- Performance Benchmarking Suite: Detailed performance analysis tools
- Visual Metrics Dashboard: Charts comparing standard vs secure clients
- Error Handling Demonstrations: Examples of handling various failure scenarios
- Best Practices Guide: Implementation patterns and security recommendations
To run the example:
cd example
flutter run
Platform Support #
| Platform | Status | Implementation |
|---|---|---|
| Android | ✅ Fully Supported | FFI + Rust + OpenSSL |
| iOS | ✅ Fully Supported | Method Channel + Swift + URLSession |
| Web | ❌ Not Supported | Browser security limitations |
| Desktop | ❌ Not Supported | Planned for future releases |
Security Considerations #
- Certificate Rotation: Use public key pinning for easier certificate updates
- Backup Pins: Consider implementing backup certificate pins for redundancy
- Pin Updates: Implement a strategy for updating certificate hashes in production
- Fallback Strategy: Plan for graceful degradation if pinning fails
- Testing: Thoroughly test pinning with staging environments before production
Troubleshooting #
Common Issues #
-
SSL Pinning Error: Certificate hash mismatch
- Verify the certificate hash is correct and up-to-date
- Check if the certificate has been renewed
-
Platform Not Supported: Using on unsupported platforms
- Ensure you're running on Android or iOS
- Check minimum version requirements
-
Network Timeouts: Slow network responses
- Consider implementing timeout handling
- Use performance benchmarking to identify bottlenecks
Contributing #
We welcome contributions! Please see our contributing guidelines and code of conduct.
License #
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog #
See CHANGELOG.md for detailed version history and updates.