How to save secret key securely in android

后端 未结 5 433
借酒劲吻你
借酒劲吻你 2021-02-05 10:38

I just read this article http://android-developers.blogspot.in/2013/02/using-cryptography-to-store-credentials.html where I learnt to generate security key.

I want to kn

5条回答
  •  囚心锁ツ
    2021-02-05 11:23

    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.

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

    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.

    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.

提交回复
热议问题