如何在android中安全地保存Oauth Access令牌

Geo*_*mas 18 android oauth access-token android-security

在身份验证之后,我可以从服务器访问令牌,"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();
Run Code Online (Sandbox Code Playgroud)

rds*_*rds 18

您无需保存访问令牌,因为它的生命周期很短.将它保存在内存中就足够了.

您确实需要保留刷新令牌,并且您有以下几种选择:

  • 在一个文件中
    • 直接在内部存储中的文件中
    • 或使用 SharedPreferences
    • 或在数据库中
  • 使用 AccountManager

考虑使用StoredCredential.对于流本身,我建议您使用Google AppAuth库.

当然,您也可以使用密码加密密钥:

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);
}
Run Code Online (Sandbox Code Playgroud)

并且密钥可以存储在KeyStore.


Jam*_*ney 5

我们使用自定义 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
Run Code Online (Sandbox Code Playgroud)

如果值是加密的,我只会推荐使用 SharedPreferences,因为即使 xml 文件仅对应用程序可用,它也可以在有 root 权限的设备上访问。

如果您已经在使用 SqlLiteDB,我可能会使用它。如果没有,仅仅保存一个令牌有点沉重。

编辑:

oauth 令牌与用于签署应用程序的密钥和密钥库完全无关。

oauth 令牌是服务器在应用程序内验证用户凭据后提供的令牌。

密钥库包含 1 个或多个用于对应用程序进行数字签名的证书。这是为了防止其他人上传与您的软件包名称相同的应用程序并替换它。