保护敏感的Android字符串是一种常见的需求,可以通过以下几种方法来实现:
示例代码:
public class Constants {
public static final String API_KEY = "your-api-key";
public static final String SECRET_KEY = "your-secret-key";
}
在ProGuard配置文件(通常是proguard-rules.pro)中添加以下内容:
-keep class com.example.Constants {
public static final *;
}
示例代码:
在本地代码中的C文件(例如:native-lib.c)中定义一个方法来获取敏感字符串:
#include
JNIEXPORT jstring JNICALL
Java_com_example_MainActivity_getApiKey(JNIEnv *env, jobject thiz) {
return (*env)->NewStringUTF(env, "your-api-key");
}
在Java代码中调用该方法:
public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
public native String getApiKey();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String apiKey = getApiKey();
// 使用获取到的敏感字符串
}
}
示例代码:
private static final String KEY_ALIAS = "my-key-alias";
public void saveApiKey(String apiKey) {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
SecretKey secretKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedKey = cipher.doFinal(apiKey.getBytes());
SharedPreferences sharedPreferences = getSharedPreferences("my-preferences", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("encrypted-api-key", Base64.encodeToString(encryptedKey, Base64.DEFAULT)).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getApiKey() {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_ALIAS, null);
Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
SharedPreferences sharedPreferences = getSharedPreferences("my-preferences", Context.MODE_PRIVATE);
String encryptedKey = sharedPreferences.getString("encrypted-api-key", "");
byte[] encryptedKeyBytes = Base64.decode(encryptedKey, Base64.DEFAULT);
byte[] apiKeyBytes = cipher.doFinal(encryptedKeyBytes);
return new String(apiKeyBytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
以上是几种保护敏感的Android字符串的解