问题
I am trying to store api keys using NDK but i tried somany methods always somany error I will share my code please any body help me..
I will share my steps i followed ..
1 Create a folder “jni” under src/main
2 Create and add “Android.mk” file under “jni” folder with following content:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := keys
LOCAL_SRC_FILES := keys.c
include $(BUILD_SHARED_LIBRARY)
Create and add “Application.mk” file under “jni” folder with the following content:
APP_ABI := all
Create the C/C++ file “keys.c” and add it under “jni” folder. Add the following content to it:
# include < jni.h > JNIEXPORT jstring JNICALL Java_com_mytest_aes_MainActivity_getNativeKey1(JNIEnv *env, jobject instance) { return (*env)->NewStringUTF(env, "haii"); }
In the Activity where you want to access the keys (in our case MainActivity), create a static block and load the library “keys” like:
static { System.loadLibrary("keys"); }
Declare two member function of type
native
to access the keys from the C/C++ file. Since we have stored 2 keys, we will declare 2 functions:public native String getNativeKey1();
For demo, access the keys in the code like:
String key1 = new String(Base64.decode(getNativeKey1(),Base64.DEFAULT)); ((TextView)findViewById(R.id.key)).setText("Key1-->"+key1);
Now, our C/C++ native files and Java code are ready. But to compile or make the native build using NDK, we need to add entry into the gradle file:
android { ..... buildTypes { ..... } externalNativeBuild { ndkBuild { path 'src/main/jni/Android.mk' } } }
We need to provide the path for our “Android.mk” file.
Now, sync and build the project. Make sure, you have pointed the NDK path correctly in your module settings.
回答1:
There are different ways in which API keys can be kept secure.
Best practice for storing and protecting private API keys in applications
Securing API Keys using Android NDK
https://medium.com/@abhi007tyagi/storing-api-keys-using-android-ndk-6abb0adcadad
Don't forget to define the NDK path correctly in your module settings. (File -> Project Structure -> SDK Location Tab -> Android NDK Location)
Note that using NDK, it's not full proof and you can still extract the keys. However, this will add an extra layer of obfuscation for your keys.
The suggested solution:- Can be used as a combination of multiple methods like Obfuscation, Encryption, Using NDK, Storing keys in Server, https integration, etc. based on the sensitivity of data in your application.
来源:https://stackoverflow.com/questions/49610269/securing-api-key-using-ndk