我在身份验证之后让服务器访问令牌"uyhjjfjfgg567f8fhjkkf"
现在我想将其安全地保存在设备中。我查看了android开发者网站中的Keystore和Keychain。我不清楚它是如何工作的以及我们应该如何从密钥库中检索令牌。
KeyPairGenerator kpg = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA512)
.build());
KeyPair kp = kpg.generateKeyPair();
/*
* Load the Android KeyStore instance using the the
* "AndroidKeyStore" provider to list out what entries are
* currently stored.
*/
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
Enumeration<String> aliases = ks.aliases();
答案 0 :(得分:15)
您不需要保存访问令牌,因为它的生命周期很短。将它保存在记忆中就足够了。
您确实需要保留刷新令牌,并且您有以下几种选择:
SharedPreferences
AccountManager
考虑使用StoredCredential
。对于流本身,我建议您使用Google AppAuth library。
当然,您也可以使用密码加密密钥:
private static byte[] encrypt(byte[] key, byte[] text) throws GeneralSecurityException {
final SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, sInitVectorSpec);
return cipher.doFinal(text);
}
密钥可以存储在KeyStore
。
答案 1 :(得分:4)
Here您可以找到Androidauthority关于Android安全可用性的非常好的文章。
可以找到Android密钥库实施的综合示例here。
另一个好的选择是Google's keyczar,您可以在git存储库中查看示例和详细信息。在那里,您还可以找到Known Security Issues的详细列表,以便了解它是否适合您的进一步实施。
对于您当前的问题,我建议您按照上面第二个链接中的示例实现继续使用Android Keystore。
祝你好运!答案 2 :(得分:3)
我们使用自定义SharedPreference实例,在添加时加密密钥和值,并在请求时解密。
SecurePreferences preferences = ...
preferences.edit().putString( "key", "value" ).apply(); // key and value are encrypted automatically
String value = preferences.getString( "key", null ); // key and value are decrypted automatically
如果值已加密,我只建议使用SharedPreferences,因为即使xml文件仅对应用程序可用,也可以在root设备上访问它。
如果您已经使用了SqlLiteDB,我可能会使用它。如果没有,只需保存一个令牌就可以了。
编辑:
oauth令牌与用于签署应用程序的密钥和密钥库完全无关。
oauth令牌是服务器在验证用户凭据后在应用程序中提供的令牌。
密钥库包含一个或多个用于对应用程序进行数字签名的证书。这是为了防止其他人上传与您的包名相同的应用并替换它。