This topic describes how to integrate the Anti-Bot SDK into Android applications.

SDK files for Android applications

Contact Alibaba Cloud technical support to obtain the SDK package, and decompress it on your local machine. The following table describes the files contained in the sdk-Android folder.

File name Description
SecurityGuardSDK-xxx.aar The main framework.
AVMPSDK-xxx.aar The virtual machine engine plug-in.
SecurityBodySDK-xxx.aar The bot recognition plug-in.
yw_1222_0335_mwua.jpg The configuration file of the virtual machine.

Configure an Android project

Configure an Android project
  1. Import the AAR files from the decompressed SDK package to Android Studio. Copy all the AAR files from the sdk-Android folder to the libs directory of the Android application project.
    Note If the libs directory does not exist in the current project, manually create a folder named libs in the specified path.
  2. Modify the configurations. Open the build.gradle file of the project and modify the configuration as follows.
    • Add the libs directory as the source for searching dependencies.
      repositories{
         flatDir {
           dirs 'libs'
         }
      }
    • Add compilation dependencies.
      Note The versions of the AAR files in this example may be different from those of the files you downloaded.
      dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile ('com.android.support:appcompat-v7:23.0.0')
        compile (name:'AVMPSDK-external-release-xxx', ext:'aar')
        compile (name:'SecurityBodySDK-external-release-xxx', ext:'aar')
        compile (name:'SecurityGuardSDK-external-release-xxx', ext:'aar')
      }
  3. Add the JPG configuration file from the decompressed SDK package to the drawable directory. Copy the yw_1222_0335_mwua.jpg configuration file in the sdk-Android folder to the drawable directory of the Android application project.
    Note If the drawable directory does not exist in the project, create a folder named drawable in the specified path.
  4. Remove redundant application binary interfaces (ABIs) because they require SO files. Currently, the Anti-Bot SDK only provides SO files for the following ABIs: armeabi, armeabi-v7a, and arm64-v8a.
    Warning Therefore, you must filter out redundant ABIs. Otherwise, the application may crash.
    1. In the libs directory of the Android application project, delete all CPU architecture files other than armeabi, armeabi-v7a, and arm64-v8a, including x86, x86_64, mips, and mips64. Keep the armeabi, armeabi-v7a, and arm64-v8a folders only.
    2. As shown in the following sample code, add filter rules to the build.gradle configuration file of the application project. Architectures specified by abiFilters are included in the Android application package (APK) file.
      Note In this example, abiFilters only specifies the armeabi architecture. You can also specify the armeabi-v7a and arm64-v8 architectures as needed.
      defaultConfig{
        applicationId "com.xx.yy"
        minSdkVersion xx
        targetSdkVersion xx
        versionCode xx
        versionName "x.x.x"
        ndk {
          abiFilters "armeabi"
          // abiFilters "armeabi-v7a"
          // abiFilters "arm64-v8a"
        }
      }
      Note If you keep the SO files of the armeabi architecture only, you can significantly reduce the size of the application without affecting its compatibility.
  5. Grant permissions to the application.
    • If you use an Android Studio project and AAR files to integrate the SDK, required permissions are already specified in the AAR files. You do not need to grant permissions to the application in the project.
    • If you use an Eclipse project, you must add the following permissions to the AndroidMenifest.xml file:
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.WRITE_SETTINGS" />
  6. Add ProGuard configurations.
    Note If you need to use ProGuard to obfuscate code, you must add ProGuard configurations. Methods to configure ProGuard in Android Studio and Eclipse are different.
    • Android Studio
      If you have set the proguardFiles parameter and the minifyEnabled parameter is set to true in the build.gradle file, the proguard-rules.pro file is used to obfuscate code.proguardFiles
    • Eclipse
      If you have configured ProGuard in the project.properties file, such as adding the proguard.config=proguard.cfg statement to the project.properties file, ProGuard is used to obfuscate code.
      Note Obfuscation configurations are specified in the proguard.cfg file.

    Add keep rules

    To guarantee that certain classes are not obfuscated, you must add the following rules to the ProGuard configuration file.
    -keep class com.taobao.securityjni.**{*;}
    -keep class com.taobao.wireless.security.**{*;}
    -keep class com.ut.secbody.**{*;}
    -keep class com.taobao.dp.**{*;}
    -keep class com.alibaba.wireless.security. **{*;}

Call the SDK

Step 1: Import packages
import com.alibaba.wireless.security.jaq.JAQException;
import com.alibaba.wireless.security.jaq.avmp.IJAQAVMPSignComponent;
import com.alibaba.wireless.security.open.SecurityGuardManager;
import com.alibaba.wireless.security.open.avmp.IAVMPGenericComponent;

Step 2: Initialize the SDK

Endpoints: boolean initialize();

Function: Initializes the SDK.

Parameters: None.

Responses: Boolean values. If the initialization is successful, true is returned. If the initialization fails, false is returned.

Sample code
IJAQAVMPSignComponent jaqVMPComp = SecurityGuardManager.getInstance(getApplicationContext()).getInterface(IJAQAVMPSignComponent.class);
boolean result = jaqVMPComp.initialize();

Step 3: Sign requests

Endpoints: byte[] avmpSign(int signType, byte[] input);

Function: Signs the input data by using the Ali Virtual Machine Protect (AVMP) technique, and returns a signature string.

Parameters
Parameter Type Required Description
signType int Yes The algorithm used to sign requests. Set the value to 3.
input byte[] No The data to be signed, which is typically the entire request body.
Note If the request body is empty, for example, an empty POST or GET request body, enter null or the value of the Bytes parameter, such as "".getBytes("UTF-8").

Responses: A signature string of the byte[] data type.

Sample code: When the client sends data to the server, it must call the avmpSign method to sign the entire request body. A wToken signature string is returned.
int VMP_SIGN_WITH_GENERAL_WUA2 = 3;
String request_body = "i am the request body, encrypted or not!" ;
byte[] result = jaqVMPComp.avmpSign(VMP_SIGN_WITH_GENERAL_WUA2, request_body.getBytes("UTF-8"));
String wToken = new String(result, "UTF-8");
Log.d("wToken", wToken);

Step 4: Add wToken to the protocol header

Add the content of the wToken field to the object of the HttpURLConnection class.

Sample code
String request_body = "i am the request body, encrypted or not!" ;
URL url = new URL("http://www.xxx.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// set wToken info to header 
conn.setRequestProperty("wToken", wToken);
OutputStream os = conn.getOutputStream();
// set request body info
byte[] requestBody = request_body.getBytes("UTF-8");
os.write(requestBody);
os.flush();
os.close();

Step 5: Send data to the server

Send data with the modified protocol header to the server of the application. Anti-Bot Service captures the data and parses the wToken to identify risks.
Warning The signed request body must be the same as the original request body that is sent by the client. The string encoding format, spaces, special characters, and parameter sequence of the signed request body must be the same as those of the original request body sent by the client. Otherwise, the request fails to pass signature verification.

Error codes

Errors may occur when you call the initialize and avmpSigni methods. If an error occurs or the SDK fails to generate a signature string, use the keyword SecException to search for relevant information in the log data.

The following table describes common error codes.

Error code Description
1901 The error code returned because the parameters are invalid. Check the parameters.
1902 The error code returned because the image file is invalid. The APK signature used to retrieve the image file is not the same as that of the application. Use the APK signature of the application to generate a new image.
1903 The error code returned because the format of the image file is invalid.
1904 Upgrade the image version. The AVMP signature function only supports v5 images.
1905 The error code returned because the specified image file cannot be found. Make sure that the image file is in the res\drawable directory, and AVMP images are in the yw_1222_0335_mwua.jpg file.
1906 The error code returned because the AVMP signature of the image does not have the required bytecode. Check whether the image is invalid.
1907 The error code returned because the initialization of AVMP failed. Try again later.
1910 The error code returned because the AVMP instance is invalid. Possible causes include:
  • The InvokeAVMP method was called after the AVMP instance had been destroyed.
  • The version of the bytecode of the image does not match the SDK.
1911 The error code returned because the bytecode of the encrypted image does not have the required export function.
1912 The error code returned because the system failed to call AVMP. Contact Alibaba Cloud technical support.
1913 The error code returned because the InvokeAVMP method was called after the AVMP instance had been destroyed.
1915 The error code returned because the memory resources of the AVMP instance are insufficient. Try again later.
1999 The error code returned because an unknown error occurred. Try again later.

Verify the integration

Take the following steps to verify that the Anti-Bot SDK has been correctly integrated into the application.

  1. Convert the packaged APK file into a ZIP file by modifying the file name extension, and decompress the file on your local machine.
  2. Go to the libs directory of the project, and make sure that the folder only contains the armeabi, armeabi-v7a, and arm64-v8a sub-folders.
    Note If any other architecture file exists, delete it. For more information, see Configure an Android project.
  3. Go to the res/drawable directory of the project, and make sure that the yw_1222_0335_mwua.jpg file exists and its size is not 0.
  4. Print the log, and make sure that the correct signature information can be generated after the avmpSign method is called.
    Note If signature information cannot be generated, see the error codes and descriptions to troubleshoot.

FAQ

Why is the key image incorrectly optimized after shrinkResources is set to true?

In Android Studio, if shrinkResources is set to true, resource files that are not referenced in the code may be optimized during project compilation. After shrinkResources is set to true, JPG files in the Anti-Bot SDK may not work as expected. If the size of the yw_1222_0335.jpg configuration file in the packaged APK is 0 KB, it indicates that the image file has been optimized.

Solutions

  1. Create a directory named raw in the res directory of the project, and create a file named keep.xml in the raw directory.
  2. Add the following content to the keep.xml file:
    <? xml version="1.0" encoding="utf-8"? >
    <resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@drawable/yw_1222_0335.jpg,@drawable/yw_1222_0335_mwua.jpg" />
  3. After you add the content, compile the project APK again.