Flutter证书锁定插件http_certificate_pinning的使用
Flutter证书锁定插件 http_certificate_pinning
的使用
概述
http_certificate_pinning
是一个用于Flutter项目的插件,它提供了HTTPS证书锁定功能。基于ssl_pinning_plugin,此插件帮助开发者确保应用与服务器之间的通信安全。
开始使用
添加依赖
在你的Flutter或Dart项目中添加以下依赖:
dependencies:
...
http_certificate_pinning: 2.0.7
获取证书指纹
要获取SHA256证书指纹,可以在控制台运行以下命令:
openssl x509 -noout -fingerprint -sha256 -inform pem -in [certificate-file.crt]
结果示例:
'59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D'
使用示例
使用Dio
import 'package:http_certificate_pinning/http_certificate_pinning.dart';
// 添加CertificatePinningInterceptor到dio客户端
Dio getClient(String baseUrl, List<String> allowedSHAFingerprints){
var dio = Dio(BaseOptions(baseUrl: baseUrl))
..interceptors.add(CertificatePinningInterceptor(allowedSHAFingerprints));
return dio;
}
myRepositoryMethod(){
dio.get("myurl.com");
}
使用Http
import 'package:http_certificate_pinning/secure_http_client.dart';
// 使用SecureHttpClient进行请求
SecureHttpClient getClient(List<String> allowedSHAFingerprints){
final secureClient = SecureHttpClient.build(certificateSHA256Fingerprints);
return secureClient;
}
myRepositoryMethod(){
secureClient.get("myurl.com");
}
自定义客户端
import 'package:http_certificate_pinning/http_certificate_pinning.dart';
Future myCustomImplementation(String url, Map<String,String> headers, List<String> allowedSHAFingerprints) async {
try{
final secure = await HttpCertificatePinning.check(
serverURL: url,
headerHttp: headers,
sha: SHA.SHA256,
allowedSHAFingerprints:allowedSHAFingerprints,
timeout : 50
);
if(secure.contains("CONNECTION_SECURE")){
return true;
}else{
return false;
}
}catch(e){
return false;
}
}
完整示例Demo
下面是一个完整的Flutter应用程序示例,展示了如何使用http_certificate_pinning
插件进行证书锁定检查:
import 'package:flutter/material.dart';
import 'package:http_certificate_pinning/http_certificate_pinning.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _PiningSslData {
String serverURL = '';
Map<String, String> headerHttp = {};
String allowedSHAFingerprint = '';
int timeout = 0;
SHA? sha;
}
class _MyAppState extends State<MyApp> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final _PiningSslData _data = _PiningSslData();
final _messengerKey = GlobalKey<ScaffoldMessengerState>();
@override
void initState() {
super.initState();
}
check(String url, String fingerprint, SHA sha, Map<String, String> headerHttp, int timeout) async {
List<String> allowedShA1FingerprintList = [];
allowedShA1FingerprintList.add(fingerprint);
try {
String checkMsg = await HttpCertificatePinning.check(
serverURL: url,
headerHttp: headerHttp,
sha: sha,
allowedSHAFingerprints: allowedShA1FingerprintList,
timeout: timeout);
if (!mounted) return;
_messengerKey.currentState?.showSnackBar(
SnackBar(
content: Text(checkMsg),
duration: const Duration(seconds: 1),
backgroundColor: Colors.green,
),
);
} catch (e) {
_messengerKey.currentState?.showSnackBar(
SnackBar(
content: Text(e.toString()),
duration: const Duration(seconds: 1),
backgroundColor: Colors.red,
),
);
}
}
void submit() {
if (_formKey.currentState?.validate() == true) {
_formKey.currentState?.save();
check(
_data.serverURL,
_data.allowedSHAFingerprint,
_data.sha ?? SHA.SHA256,
_data.headerHttp,
_data.timeout,
);
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: _messengerKey,
home: Scaffold(
appBar: AppBar(
title: const Text('Ssl Pinning Plugin'),
),
body: Builder(
builder: (BuildContext context) {
return Container(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
TextFormField(
keyboardType: TextInputType.url,
controller: TextEditingController(text: "https://google.com"),
decoration: const InputDecoration(
hintText: 'https://yourdomain.com',
labelText: 'URL',
),
validator: (value) {
if (value?.isEmpty == true) {
return 'Please enter some url';
}
return null;
},
onSaved: (value) {
_data.serverURL = value ?? '';
},
),
DropdownButton(
items: [
DropdownMenuItem(
child: Text(SHA.SHA1.toString()),
value: SHA.SHA1,
),
DropdownMenuItem(
child: Text(SHA.SHA256.toString()),
value: SHA.SHA256,
)
],
value: _data.sha,
isExpanded: true,
onChanged: (SHA? val) {
setState(() {
_data.sha = val;
});
},
),
TextFormField(
controller: TextEditingController(
text: "51 E9 01 5F FE FB 79 70 D8 DF 74 BB 46 94 63 72 B1 E3 2B 31 6A 46 F0 C5 36 E7 C1 D4 DD C5 B2 70"),
keyboardType: TextInputType.text,
decoration: const InputDecoration(
hintText: 'OO OO OO OO OO OO OO OO OO OO',
labelText: 'Fingerprint',
),
validator: (value) {
if (value?.isEmpty == null) {
return 'Please enter some fingerprint';
}
return null;
},
onSaved: (value) {
_data.allowedSHAFingerprint = value ?? '';
},
),
TextFormField(
keyboardType: TextInputType.number,
initialValue: '60',
decoration: const InputDecoration(
hintText: '60',
labelText: 'Timeout',
),
validator: (value) {
if (value?.isEmpty == true) {
return 'Please enter some timeout';
}
return null;
},
onSaved: (value) {
_data.timeout = int.tryParse(value ?? '') ?? 0;
},
),
Container(
margin: const EdgeInsets.only(top: 20.0),
child: ElevatedButton(
onPressed: () => submit(),
child: const Text(
'Check',
style: TextStyle(
color: Colors.white,
),
),
),
)
],
),
),
);
},
),
),
);
}
}
这个示例展示了如何集成和使用http_certificate_pinning
插件来实现SSL证书锁定检查。你可以根据自己的需求调整代码中的细节。
更多关于Flutter证书锁定插件http_certificate_pinning的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter证书锁定插件http_certificate_pinning的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用http_certificate_pinning
插件进行证书锁定的代码示例。这个插件允许你为你的HTTP请求添加证书锁定,从而确保你的应用只与受信任的服务器通信。
步骤1:添加依赖
首先,你需要在你的pubspec.yaml
文件中添加http_certificate_pinning
依赖:
dependencies:
flutter:
sdk: flutter
http_certificate_pinning: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
步骤2:配置插件
接下来,你需要将你的服务器证书(通常是.pem
文件)添加到你的Flutter项目中。假设你有一个名为server.pem
的证书文件,你可以将它放在assets
目录下(如果没有这个目录,你需要创建一个)。
确保在pubspec.yaml
中声明这个资产:
flutter:
assets:
- assets/server.pem
步骤3:使用插件
在你的Dart代码中,你可以按照以下方式使用http_certificate_pinning
插件:
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http_certificate_pinning/http_certificate_pinning.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Certificate Pinning Example'),
),
body: Center(
child: FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Data: ${snapshot.data}');
}
} else {
return CircularProgressIndicator();
}
},
),
),
),
);
}
Future<String> fetchData() async {
// 加载证书
final ByteData byteData = await rootBundle.load('assets/server.pem');
final String pemCert = byteData.buffer.asUint8List().toBase64().split('\n').join('');
// 配置证书锁定
final httpPinning = HttpCertificatePinning(
certPins: [pemCert],
hostname: 'your.server.com', // 替换为你的服务器地址
port: 443, // 默认HTTPS端口
);
// 创建HTTP客户端
final client = httpPinning.createClient();
// 发送请求
final response = await client.get(Uri.parse('https://your.server.com/endpoint'));
// 处理响应
if (response.statusCode == 200) {
return await response.body.decodeString();
} else {
throw Exception('Failed to load data: ${response.statusCode}');
}
}
}
注意事项
-
证书格式:确保你的证书是以PEM格式存储的。如果证书是其他格式(如DER),你可能需要将其转换为PEM格式。
-
证书链:如果你的服务器使用证书链,你可能需要包含整个证书链(包括根证书、中间证书和服务器证书)在
.pem
文件中。 -
错误处理:在实际应用中,你应该添加更详细的错误处理逻辑,以便在证书验证失败时给用户一个清晰的反馈。
-
安全性:证书锁定是保护你的应用免受MITM攻击的一种有效方式。然而,它并不能替代HTTPS的其他安全措施,如使用强密码套件和定期更新证书。
通过以上步骤,你应该能够在Flutter应用中成功实现证书锁定。