Skip to content

Instantly share code, notes, and snippets.

@alome007
Last active January 19, 2023 14:55
Show Gist options
  • Save alome007/5de77898feb79138c3d19ee34d7e3ea4 to your computer and use it in GitHub Desktop.
Save alome007/5de77898feb79138c3d19ee34d7e3ea4 to your computer and use it in GitHub Desktop.
SharedPreferencesHelper demonstrating how to use EncryptedSharedPreferences
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
class SharedPreferencesHelper {
private val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
fun saveData(context: Context, key:String ,data: String){
// Initialize/open an instance of EncryptedSharedPreferences on below line.
val sharedPreferences = EncryptedSharedPreferences.create(
// passing a file name to share a preferences
FILE_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().putString(key, data).apply()
}
fun getData(context: Context, key: String): String? {
// Initialize/open an instance of EncryptedSharedPreferences on below line.
val sharedPreferences = EncryptedSharedPreferences.create(
// passing a file name to share a preferences
FILE_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
// on below line creating a variable
// to get the data from shared prefs.
return sharedPreferences.getString(key, "")
}
companion object {
const val FILE_NAME = "My_file_name"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment