How Can I Use the Android KeyStore to securely store arbitrary strings?

后端 未结 3 2179
Happy的楠姐
Happy的楠姐 2020-11-28 03:12

I would like to be able securely store some sensitive strings in the Android KeyStore. I get the strings from the server but I have a use case which requires me to persist t

3条回答
  •  盖世英雄少女心
    2020-11-28 03:49

    You may have noticed that there are problems handling different API levels with the Android Keystore.

    Scytale is an open source library that provides a convenient wrapper around the Android Keystore so that you don't have write boiler plate and can dive straight into enryption/decryption.

    Sample code:

    // Create and save key
    Store store = new Store(getApplicationContext());
    if (!store.hasKey("test")) {
       SecretKey key = store.generateSymmetricKey("test", null);
    }
    ...
    
    // Get key
    SecretKey key = store.getSymmetricKey("test", null);
    
    // Encrypt/Decrypt data
    Crypto crypto = new Crypto(Options.TRANSFORMATION_SYMMETRIC);
    String text = "Sample text";
    
    String encryptedData = crypto.encrypt(text, key);
    Log.i("Scytale", "Encrypted data: " + encryptedData);
    
    String decryptedData = crypto.decrypt(encryptedData, key);
    Log.i("Scytale", "Decrypted data: " + decryptedData);
    

提交回复
热议问题