Skip to content

Instantly share code, notes, and snippets.

@gauravssnl
Forked from scottyab/SampleEncPrefs.kt
Created January 30, 2024 15:23
Show Gist options
  • Save gauravssnl/803917898b4d6589135fef082de163b2 to your computer and use it in GitHub Desktop.
Save gauravssnl/803917898b4d6589135fef082de163b2 to your computer and use it in GitHub Desktop.

Revisions

  1. @scottyab scottyab created this gist Jul 24, 2019.
    47 changes: 47 additions & 0 deletions SampleEncPrefs.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    package com.scottyab.whatsnewplayground.data

    import android.content.Context
    import android.content.SharedPreferences
    import androidx.security.crypto.EncryptedSharedPreferences
    import androidx.security.crypto.MasterKeys
    import com.scottyab.whatsnewplayground.BuildConfig

    internal class SampleEncPrefs(context: Context) {

    private val sharedPrefs: SharedPreferences

    init {
    val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
    val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)

    sharedPrefs = EncryptedSharedPreferences
    .create(
    FILENAME,
    masterKeyAlias,
    context,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
    }

    var userId: String
    get() = sharedPrefs.getStringOrEmpty(USER_ID)
    set(value) = sharedPrefs.edit().putString(USER_ID, value).apply()

    var email: String
    get() = sharedPrefs.getStringOrEmpty(EMAIL)
    set(value) = sharedPrefs.edit().putString(EMAIL, value).apply()

    var accessToken: String
    get() = sharedPrefs.getStringOrEmpty(TOKEN)
    set(value) = sharedPrefs.edit().putString(TOKEN, value).apply()

    private fun SharedPreferences.getStringOrEmpty(key: String): String = getString(key, "") ?: ""

    companion object {
    private const val FILENAME = "my.secure.sharedPrefs"
    private const val USER_ID = BuildConfig.APPLICATION_ID + ".USER_ID"
    private const val EMAIL = BuildConfig.APPLICATION_ID + ".EMAIL"
    private const val TOKEN = BuildConfig.APPLICATION_ID + ".TOKEN"
    }
    }