如何在android中安全地保存Oauth访问令牌 [英] How to save Oauth Access token securely in android
问题描述
我在身份验证后从服务器获得访问令牌可以说 "uyhjjfjfgg567f8fhjkkf"
现在我想将它安全地保存在设备中.我在 android 开发者网站上查看了 Keystore 和 Keychain.我不清楚它是如何工作的以及我们应该如何从密钥库中检索令牌.
I have access token from the server after authentication lets say "uyhjjfjfgg567f8fhjkkf"
now I want to save it in the device securely. I looked in Keystore and Keychain in android developer sites. I dont clearly understand how it works and how we should retrieve the token from the keystore.
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();
推荐答案
您不需要保存访问令牌,因为它的生命周期很短.将它保存在内存中就足够了.
You don't need to save the access token, since it has short life anyway. Keeping it in memory is good enough.
您确实需要保留刷新令牌,为此您有几个选择:
You do need to keep the refresh token, and you have a few options for that:
- 在一个文件中
- 直接在内部存储的文件中
- 或使用
SharedPreferences
- 或在数据库中
考虑使用
StoredCredential
.对于流程本身,我建议您使用 Google AppAuth 库.当然,您也可以使用密码来加密密钥:
Of course, you can also encrypt the key using a cipher:
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
中.And the key can be stored in the
KeyStore
.这篇关于如何在android中安全地保存Oauth访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!