在一个应用程序中,我使用了 Android KeyStore。我已经为整个 KeyStore 和每个密码条目设置了密码。由于这些密码是字符串,因此它们存储在代码中的字符串成员中。
显然,如果我想发布应用程序,这并不安全,因为潜在的攻击者可以反编译 apk 并获取密码,因为它是硬编码在应用程序中的。
我的问题是:
- 在上面的场景中:攻击者是否能够读取我的 keystore 文件,或者(在无根电话上)该文件是否只能由我的应用程序访问,因此仅凭密码是不够的?
- 处理 KeyStore 密码的最佳做法是什么?我环顾四周,但没有找到如何处理这个问题的明确答案。
为澄清而编辑:我不谈论应用程序签名,而是谈论将加密 key 存储在受密码保护的 Android KeyStore 中。应用程序必须在运行时访问密码才能检索 key 条目。
当前代码示例:
String keyStorePwd = "password1";
String keyEntryPwd = "password2";
FileInputStream fis = getApplicationContext().openFileInput("sms.keystore");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(fis, keyStorePwd.toCharArray());
SecretKey key = (SecretKey) ks.getKey("aes_key_sms_notifier", keyEntryPwd.toCharArray());
fis.close();
最佳答案
不建议在您的 APK 中存储密码。当我们谈论 keystore 密码时更多。是的,攻击者可以而且将会找到读取密码的方法,因为他们就是这样做的。鲁莽地阅读 APK 中包含的密码。假设您使用 gradle,有一种使用 gradle 指定的方法来存储 keystore 密码。
属性文件
如果您使用的是版本控制,请修改您的 .gitignore
文件以排除 keystore.properties
,该文件将包含您的密码。然后将其推送到 repo 协议(protocol)中。这样做将防止共享项目中的其他开发人员知道 keystore 的详细信息。您现在可以在项目的根目录中创建实际的 keystore.properties
文件。该文件应包含以下内容:
keyAlias yourKeyAlias
keyPassword yourKeyPassword
storeFile pathOfYourKeyStoreFile
storePassword passwordOfYourKeyStoreFile
渐变
设置完 keystore.properties
文件后,通过在 android { ... }
子句之外定义一个属性变量来修改模块级 gradle 构建文件,例如:
def keystorePropertiesFile= rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
android { ... }
在 android { ... }
中,声明 signingConfigs { ... }
这样:
android {
signingConfigs {
config {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
...........
}
最后,仍然在模块级 gradle 构建文件的 android { ... }
中,您应该有 buildTypes { ... }
子句默认包含 debug { ... }
和 release { ... }
配置。修改 release
配置,这样:
buildTypes {
debug {
*insert debug configs here*
}
release {
*insert release configs here*
signingConfig signingConfigs.config
}
}
在 release { ... }
中定义 signingConfig signingConfigs.config
将允许您在选择创建发布版本时自动签署 APK,所有这些都无需将您的 keystore 密码存储在您的 APK 中。干杯!
关于android - 如何安全地存储 Android KeyStore 密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691000/