Most app developers will integrate some third party libraries into their apps. If it's to access a service, such as Dropbox or YouTube, or for logging crashes. The number of third party libraries and services is staggering. Most of those libraries and services are integrated by somehow authenticating with the service, most of the time, this happens through an API key. For security purposes, services usually generate a public and private, often also referred to as secret, key. Unfortunately, in order to connect to the services, this private key must be used to authenticate and hence, probably be part of the application.
Needless to say, that this faces in immense security problem. Public and private API keys can be extracted from APKs in a matter of minutes and can easily be automated.
假设我有类似的东西,我如何保护密钥:
public class DropboxService {
private final static String APP_KEY = "jk433g34hg3";
private final static String APP_SECRET = "987dwdqwdqw90";
private final static AccessType ACCESS_TYPE = AccessType.DROPBOX;
// SOME MORE CODE HERE
}
你认为储存私钥的最佳及最安全的方法是什么?混淆,加密,你怎么看?
旧的不安全的方式:
遵循3个简单的步骤来保护API/密钥(旧答案)
我们可以使用Gradle来保护API密钥或秘密密钥。
1. gradle。properties(项目属性):创建带有key的变量。
GoogleAPIKey = "Your API/Secret Key"
2. 构建。gradle (Module: app):在build中设置变量。Gradle在活动或片段中访问它。将以下代码添加到buildTypes{}。
buildTypes.each {
it.buildConfigField 'String', 'GoogleSecAPIKEY', GoolgeAPIKey
}
3.通过应用程序的BuildConfig在Activity/Fragment中访问它:
BuildConfig.GoogleSecAPIKEY
更新:
上述解决方案对通过Git提交的开源项目很有帮助。(感谢David Rawson和riyazi -ali的评论)。
根据Matthew和Pablo Cegarra的评论,上述方式是不安全的,反编译器将允许某人使用我们的密钥查看BuildConfig。
解决方案:
我们可以使用NDK来保护API密钥。我们可以在原生C/ c++类中存储键,并在Java类中访问它们。
请跟随这个博客使用NDK保护API密钥。
关于如何在Android中安全地存储令牌的后续内容
很少有想法,在我看来,只有第一个想法给了一些保证:
Keep your secrets on some server on internet, and when needed just grab them and use. If user is about to use dropbox then nothing stops you from making request to your site and get your secret key.
Put your secrets in jni code, add some variable code to make your libraries bigger and more difficult to decompile. You might also split key string in few parts and keep them in various places.
use obfuscator, also put in code hashed secret and later on unhash it when needed to use.
Put your secret key as last pixels of one of your image in assets. Then when needed read it in your code. Obfuscating your code should help hide code that will read it.
如果你想快速看看阅读你的apk代码是多么容易,然后获取APKAnalyser:
http://developer.sonymobile.com/knowledge-base/tool-guides/analyse-your-apks-with-apkanalyser/