Hiding Secret/Api key from reverse engineering in Android using NDK
Loosing secret key, Api keys can create a serious privacy issue or may effect the billing of your app. So to secure this we will use NDK.
Below are the steps to secure hardcoded string from reverse engineering.
- We need a jni(Java Native Interface) folder under src folder which contain three files : Android.mk, Application.mk, Keys.c as shown is below screen shot
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := keys
LOCAL_SRC_FILES := keys.c
include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_ABI := all
Keys.c
JNIEXPORT jstring JNICALL
Java_com_my_app_Keys_getFirstKey(JNIEnv *env, jclass instance) {
return (*env)->NewStringUTF(env, "abcd1234567890");
}JNIEXPORT jstring JNICALL
Java_com_my_app_Keys_getSecondKey(JNIEnv *env, jclass instance) {
return (*env)->NewStringUTF(env, "abcde12345");
}
com_my_app : package name
Keys : class name
getFirstKey : method name
Edit app level build.gradle file with below code to compile NDK code
android {...
externalNativeBuild {
ndkBuild {
path 'src/main/jni/Android.mk'
}
}
}
To use the NDK method in android, I am creating a separate class names Keys.java, and the method to read string from Keys.c file
Keys.java
private static native String getFirstKey();
private static String readFirstKey() {//use this method for String
return getFirstKey();
}
To load .so file in memory we have to invoke in application class
static {
System.loadLibrary("keys");
}
Do comments if having any doubts or required improvements, claps will motivate me.
I have already covered, Why we have to hide string and which method we have to use.