Flutter安全检测插件huawei_safetydetect的使用
Flutter安全检测插件huawei_safetydetect的使用
安装
请参阅以下链接进行安装:
文档
以下是一些有用的文档链接:
问题或建议
如果您在使用HMS样本时遇到任何问题,可以尝试以下选项:
- 在Stack Overflow上提问,并确保您的问题标签为 huawei-mobile-services。
- 在Github上提交问题或提出您的想法。
- 在Huawei Developer Forum上提问或寻求建议。
- 查看Huawei Developer Docs获取所有HMS核心套件的官方文档。
如果在示例中遇到任何错误,请提交一个GitHub仓库的问题。
许可证
Huawei Safety Detect Flutter插件遵循Apache 2.0许可证。
完整示例代码
/*
Copyright 2020-2022. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huawei_safetydetect/huawei_safetydetect.dart';
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
[@override](/user/override)
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final List<String> logs = [];
late final String appId;
[@override](/user/override)
void initState() {
super.initState();
SafetyDetect.getAppID.then((String appId) {
this.appId = appId;
log('getAppID', 'App Id: $appId');
}).catchError((dynamic e) {
log('getAppID', e, false);
});
}
Future<dynamic> isVerifyAppsCheck() async {
return await SafetyDetect.isVerifyAppsCheck();
}
Future<dynamic> enableAppsCheck() async {
return await SafetyDetect.enableAppsCheck();
}
Future<dynamic> initUrlCheck() async {
return await SafetyDetect.initUrlCheck();
}
Future<dynamic> shutdownUrlCheck() async {
return await SafetyDetect.shutdownUrlCheck();
}
Future<dynamic> urlCheck() async {
const String url = 'http://example.com/hms/safetydetect/malware';
final List<UrlCheckThreat> result = await SafetyDetect.urlCheck(
url,
appId,
[UrlThreatType.malware, UrlThreatType.phishing],
);
return '${result.length} threat is detected for the URL: $url';
}
Future<dynamic> initUserDetect() async {
return await SafetyDetect.initUserDetect();
}
Future<dynamic> shutdownUserDetect() async {
return await SafetyDetect.shutdownUserDetect();
}
Future<dynamic> userDetection() async {
final String? token = await SafetyDetect.userDetection(appId);
return 'User verified, user token: $token';
}
Future<dynamic> initAntiFraud() async {
return await SafetyDetect.initAntiFraud(appId);
}
Future<dynamic> releaseAntiFraud() async {
return await SafetyDetect.releaseAntiFraud();
}
Future<dynamic> getRiskToken() async {
final String? riskToken = await SafetyDetect.getRiskToken();
return 'Risk Token: $riskToken';
}
Future<dynamic> sysIntegrity() async {
final List<int> randomIntegers = [];
for (int i = 0; i < 24; i++) {
randomIntegers.add(math.Random.secure().nextInt(255));
}
final Uint8List nonce = Uint8List.fromList(randomIntegers);
final String result = await SafetyDetect.sysIntegrity(
nonce,
appId,
alg: 'RS256',
);
final List<String> jwsSplit = result.split('.');
final String decodedText = utf8.decode(base64Url.decode(jwsSplit[1]));
return json.decode(decodedText);
}
Future<dynamic> getWifiDetectStatus() async {
final WifiDetectResponse status = await SafetyDetect.getWifiDetectStatus();
return 'Wifi detect status is: ${status.getWifiDetectType}';
}
Future<dynamic> getMaliciousAppsList() async {
final List<MaliciousAppData> result = await SafetyDetect.getMaliciousAppsList();
return '${result.length} malicious apps detected.';
}
void log(String method, dynamic message, [bool isSuccess = true]) {
final String status = isSuccess ? 'SUCCESS' : 'FAILURE';
final String logMessage = '$status\n${message ?? ''}'.trim();
developer.log(logMessage, name: method);
setState(() => logs.insert(0, '[$method]: $logMessage'));
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Tooltip(
message: 'Flutter Version: 6.4.0+302',
child: Text('HMS Safety Detect Demo'),
),
),
body: Column(
children: [
Expanded(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
physics: const BouncingScrollPhysics(),
child: Wrap(
spacing: 16,
alignment: WrapAlignment.center,
children: [
buildButton(
text: 'isVerifyAppsCheck',
onPressed: isVerifyAppsCheck,
),
buildButton(
text: 'enableAppsCheck',
onPressed: enableAppsCheck,
),
const Divider(),
buildButton(
text: 'initUrlCheck',
onPressed: initUrlCheck,
),
buildButton(
text: 'shutdownUrlCheck',
onPressed: shutdownUrlCheck,
),
buildButton(
text: 'urlCheck',
onPressed: urlCheck,
),
const Divider(),
buildButton(
text: 'initUserDetect',
onPressed: initUserDetect,
),
buildButton(
text: 'shutdownUserDetect',
onPressed: shutdownUserDetect,
),
buildButton(
text: 'userDetection',
onPressed: userDetection,
),
const Divider(),
buildButton(
text: 'initAntiFraud',
onPressed: initAntiFraud,
),
buildButton(
text: 'releaseAntiFraud',
onPressed: releaseAntiFraud,
),
buildButton(
text: 'getRiskToken',
onPressed: getRiskToken,
),
const Divider(),
buildButton(
text: 'sysIntegrity',
onPressed: sysIntegrity,
),
buildButton(
text: 'getWifiDetectStatus',
onPressed: getWifiDetectStatus,
),
buildButton(
text: 'getMaliciousAppsList',
onPressed: getMaliciousAppsList,
),
],
),
),
),
),
const Divider(),
buildLogcat(),
],
),
);
}
Widget buildButton({
required String text,
required Future<dynamic> Function() onPressed,
}) {
return ElevatedButton(
onPressed: () async {
try {
final dynamic result = await onPressed.call();
log(text, result);
} catch (e) {
log(text, e, false);
}
},
child: Text(text),
);
}
Widget buildLogcat() {
return GestureDetector(
onDoubleTap: () => setState(() => logs.clear()),
child: AspectRatio(
aspectRatio: 2,
child: Container(
alignment: Alignment.center,
margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.10),
borderRadius: const BorderRadius.all(Radius.circular(16)),
),
child: logs.isEmpty
? const Text('Double tap to clear logs')
: ListView.separated(
physics: const BouncingScrollPhysics(),
itemCount: logs.length,
itemBuilder: (_, int index) => Text(logs[index]),
separatorBuilder: (_, __) => const Divider(),
),
),
),
);
}
}
更多关于Flutter安全检测插件huawei_safetydetect的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter安全检测插件huawei_safetydetect的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用huawei_safetydetect
插件来进行安全检测的示例代码。这个插件主要用于集成华为的安全检测服务,比如应用完整性检测、恶意应用检测等。
首先,确保你的Flutter项目已经正确配置了华为移动服务(HMS)SDK。这通常涉及在build.gradle
文件中添加依赖,以及在华为开发者平台上为你的应用配置相关信息。
步骤 1: 添加依赖
在你的pubspec.yaml
文件中添加huawei_safetydetect
依赖:
dependencies:
flutter:
sdk: flutter
huawei_safetydetect: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
步骤 2: 配置Android项目
在android/app/build.gradle
文件中添加华为移动服务的配置:
android {
...
defaultConfig {
...
applicationId "com.example.yourapp" // 替换为你的应用ID
...
manifestPlaceholders = [
'appid': '你的华为应用ID', // 替换为你的华为应用ID
'cpackage': 'com.example.yourapp' // 替换为你的应用包名
]
}
...
}
dependencies {
implementation 'com.huawei.hms:safetydetect:x.y.z' // 请替换为最新版本号
...
}
步骤 3: 使用huawei_safetydetect
插件
在你的Flutter代码中,你可以这样使用huawei_safetydetect
插件来进行安全检测:
import 'package:flutter/material.dart';
import 'package:huawei_safetydetect/huawei_safetydetect.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String result = '';
@override
void initState() {
super.initState();
_checkAppIntegrity();
}
Future<void> _checkAppIntegrity() async {
try {
bool isIntegrityVerified = await SafetyDetect.appsCheck(checkType: AppsCheckType.verifyApps);
setState(() {
result = isIntegrityVerified ? '应用完整性验证通过' : '应用完整性验证失败';
});
} catch (e) {
setState(() {
result = '安全检测失败: ${e.message}';
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('华为安全检测示例'),
),
body: Center(
child: Text(result),
),
),
);
}
}
在这个示例中,我们使用了SafetyDetect.appsCheck
方法来检查应用的完整性。checkType
参数指定了检查的类型,这里我们使用verifyApps
来进行应用完整性验证。根据验证结果,我们更新UI显示相应的信息。
注意事项
- 权限声明:确保你的
AndroidManifest.xml
文件中已经声明了必要的权限。 - 签名证书:使用华为安全检测服务时,你的应用需要使用华为开发者平台上配置的签名证书进行签名。
- 版本兼容性:确保你的应用和设备上的华为移动服务SDK版本兼容。
这个示例代码展示了如何在Flutter应用中使用huawei_safetydetect
插件进行基本的安全检测。根据你的需求,你还可以探索更多高级功能,比如恶意应用检测、设备安全检测等。