[Huawei Developers] shikkerimath:
Introduction

In this article, we will learn how to implement Huawei Safety detect kit in to mobile applications. Mobile devices have become more popular than laptops. Now a days users engage in nearly all activities on mobile devices, right from watching the news, checking emails, online shopping, doing bank transactions. Through these apps, business can gather usable information, which can help business to take precise decisions for better services.

View attachment 5263169

What is Huawei Safety Detect Service?

Safety Detect builds robust security capabilities, including system integrity check (SysIntegrity), app security check (AppsCheck), malicious URL check (URLCheck), fake user detection (UserDetect), and malicious Wi-Fi detection (WifiDetect), into your app, effectively protecting it against security threats.

1. SysIntegrity API: Checks whether the device running your app is secure, for example, whether it is rooted.

2. AppsCheck API: Checks for malicious apps and provides you with a list of malicious apps.

3. URLCheck API: Determines the threat type of a specific URL.

4. UserDetect API: Checks whether your app is interacting with a fake user.

5. WifiDetect API: Checks whether the Wi-Fi to be connected is secure.

Why Security is required for Apps

Mobile app security is a measure to secure application from threats like malware and other digital frauds that risk critical personal and financial information from hackers to avoid all of these we need to integrate the safety detect.

What are all the restrictions exists?

Currently two restrictions are there WifiDetect and UserDetect.

1. WifiDetect function available only in Chinese mainland.

2. UserDetect function not available in Chinese mainland.

Advantages

1. Provides a Trusted Execution Environment (TEE) to check system integrity.

2. Makes building security into your app easy with a rapid integration wizard.

3. Checks security for a diversity of apps: e-commerce, finance, multimedia, and news.

Requirements

1. Any operating system(i.e. MacOS, Linux and Windows)

2. Any IDE with Flutter SDK installed (i.e. IntelliJ, Android Studio and VsCode etc.)

3. A little knowledge of Dart and Flutter.

4. A Brain to think

Setting up the project

View attachment 5263167

1. Before start creating application we have to make sure we connect our project to AppGallery. For more information check this link

2. After that follow the URL for cross-platform plugins. Download required plugins.

3. Enable the Safety Detect in the Manage API section and add the plugin.

4. After completing all the above steps, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.

huawei_safetydetect:
path: ../huawei_safetydetect/

After adding them, run flutter pub get command. Now all the plugins are ready to use.

Note: Set multiDexEnabled to true in the android/app directory, so the app will not crash.

Why we need SysIntegrity API and How to Use?

The SysIntegrity API is called to check the system integrity of a device. If the device is not safe, appropriate measures are taken.

Before implementing this API we need to check device have latest version of HMS core must be installed on users device.

Obtain a nonce value will be used to determine whether the returned result corresponds to the request and did not encounter and replay attacks. The nonce value must contain a minimum of 16 bytes and is intended to be used only once. Request for the AppId as input parameters.

getAppId() async {
String appID = await SafetyDetect.getAppID;
setState(() {
appId = appID;
});
}

checkSysIntegrity() async {
Random secureRandom = Random.secure();
List randomIntegers = List<int>();
for (var i = 0; i < 24; i++) {
randomIntegers.add(secureRandom.nextInt(255));
}
Uint8List nonce = Uint8List.fromList(randomIntegers);
try {
String result = await SafetyDetect.sysIntegrity(nonce, appId);
List<String> jwsSplit = result.split(".");
String decodedText = utf8.decode(base64Url.decode(jwsSplit[1]));
showToast("SysIntegrityCheck result is: $decodedText");
} on PlatformException catch (e) {
showToast("Error occured while getting SysIntegrityResult. Error is : $e");
}
}
}

Why we need AppsCheck API and How to Use?

You can obtain all malicious applications and evaluate whether you can restrict the behaviour of your application based on the risk.

You can directly call the getMaliciousAppsList() method to get all the malicious apps.

void getMaliciousAppsList() async {
List<MaliciousAppData> maliciousApps = List();
maliciousApps = await SafetyDetect.getMaliciousAppsList();
setState(() {
showToast("malicious apps: ${maliciousApps.toString()}");
});
}

In the return from task, you will get a list of malicious applications. You can find out the package name, SHA256 value and category of an application in this list.

Why we need User Detect API and How to Use?

This API can help your app prevent batch registration, credential stuffing attacks, activity bonus hunting, and content crawling. If a user is a suspicious one or risky one, a verification code is sent to the user for secondary verification. If the detection result indicates that the user is a real one, the user can sign in to my app. Otherwise, the user is not allowed to MainPage.

void _signInHuawei() async {
final helper = new HmsAuthParamHelper();
helper
..setAccessToken()
..setIdToken()
..setProfile()
..setEmail()
..setAuthorizationCode();
try {
HmsAuthHuaweiId authHuaweiId =
await HmsAuthService.signIn(authParamHelper: helper);
StorageUtil.putString("Token", authHuaweiId.accessToken);
} on Exception catch (e) {}
}

userDetection() async {
try {
String token = await SafetyDetect.userDetection(appId);
print("User verification succeded, user token: $token");
if(token!=null){
userDetection();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePageScreen()),
);
}
} on PlatformException catch (e) {
print(
"Error occurred: " + e.code + ":" + SafetyDetectStatusCodes[e.code]);
}
}

Why we need URLCheck API and How to Use?

You can determine the dangerous urls using URL Check API. Currently UrlSafety API provide determinate MALWARE and PHISHING threats. When you visit a URL, this API checks whether the URL is a malicious one. If so, you can evaluate the risk and alert the user about the risk or block the URL.

InkWell(
onTap: () {
loadUrl();
},
child: Text(
'Visit: $url',
style:
TextStyle(color: textColor),
))
void loadUrl() async {
Future.delayed(const Duration(seconds: 5), () async {
urlCheck();
});
}

void urlCheck() async {
List<UrlThreatType> threatTypes = [
UrlThreatType.malware,
UrlThreatType.phishing
];

List<UrlCheckThreat> urlCheckResults =
await SafetyDetect.urlCheck(url, appId, threatTypes);

if (urlCheckResults.length == 0) {
showToast("No threat is detected for the URL");
} else {
urlCheckResults.forEach((element) {
print("${element.getUrlThreatType} is detected on the URL");
});
}
}

Why we need WifiDetect API and How to Use?

This API checks characteristics of the Wi-Fi and router to be connected, analyzes the Wi-Fi information, and returns the Wi-Fi detection results after classification, helping you prevent possible attacks to your app from malicious Wi-Fi. If attacks are detected app can interrupt the user operation or it will asks user permission.

@override
void initState() {
getWifiDetectStatus();
super.initState();
}

getWifiDetectStatus() async {
try {
WifiDetectResponse wifiDetectStatus =
await SafetyDetect.getWifiDetectStatus();
ApplicationUtils.displayToast(
'Wifi detect status is: ${wifiDetectStatus.getWifiDetectType.toString()}');
} on PlatformException catch (e) {
if (e.code.toString() == "19003") {
ApplicationUtils.displayToast(' The WifiDetect API is unavailable in this region');
}
}
}

Note: Currently this API supports Chinese mainland.

Demo

View attachment 5263165

Tips & Tricks

1. Download latest HMS Flutter plugin.

2. Set minSDK version to 19 or later.

3. Do not forget to click pug get after adding dependencies.

4. Latest HMS Core APK is required.

Conclusion

These were some of the best practices that a mobile app developer must follow in order to have a fully secure and difficult-to-crack application.

In the near future, security will act as one of the differentiating and competing innovations in the app world, with customers preferring secure apps to maintain the privacy of their data over other mobile applications.

Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment 💬 below.

Reference

Safety detect Kit URL

Checkout in forum