且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Android中安全保存密钥

更新时间:2023-02-16 07:55:05

这是保持对敏感数据的访问的总体问题.总有一种解密方法,然后加密密钥可能会泄漏.

This is the overall problem with keeping access to the sensitive data. There is always a way to decrypt, then the encryption key might leak.

您可以使用 EncryptedPreferences 以加密方式存储简单数据.

You might use EncryptedPreferences to store simple data in an encrypted way.

但是,只要快速查看源代码,您就必须在应用程序init上传递密码.

However just a quick look into source code reveals, that you must pass a password on app init.

EncryptedPreferences encryptedPreferences = new EncryptedPreferences.Builder(this).withEncryptionPassword("password").build();

如果密码是硬编码的,这是安全漏洞.这不是首选方法.

This is security leak, if the password is hardcoded. This is not preferred method.

您可以利用您提供的链接并生成一次性垫子.

You might make use of the link you provided and generate a One-time pad.

public static SecretKey generateKey() throws NoSuchAlgorithmException {
    // Generate a 256-bit key
    final int outputKeyLength = 256;

    SecureRandom secureRandom = new SecureRandom();
    // Do *not* seed secureRandom! Automatically seeded from system entropy.
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(outputKeyLength, secureRandom);
    SecretKey key = keyGenerator.generateKey();
    return key;
}

当然要考虑理想情况,其中密钥生成函数在理想情况下是随机的.

Of course an ideal situation is taken into account, where the key generating function is ideally random.

在第一次启动应用程序时生成此密钥,并在我之前提供的链接库中使用它.

Generate this key on first application start and use it in the library, which link I provided before.

优势:对于每个应用程序安装,密钥都不同.这意味着,如果破解者知道密码的工作方式,只要他无法访问该设备的 SharedPreferences ,他仍然无法解密其他设备.

Advantage: the key is different for each application installation. That means if the cracker got to know the method how cipher works, he is still unable to decrypt other devices as long as he does not have an access to such device's SharedPreferences.