Skip to content

Instantly share code, notes, and snippets.

@marcusmotill
Created March 12, 2016 18:46
Show Gist options
  • Save marcusmotill/2a3cd35c99b5b668bbb5 to your computer and use it in GitHub Desktop.
Save marcusmotill/2a3cd35c99b5b668bbb5 to your computer and use it in GitHub Desktop.
Secure User Storage
class SecureUserStorage {
fun putUser(user: User, context: Context) {
val sharedpreferences = context.getSharedPreferences("userPrefs", Context.MODE_PRIVATE)
val crypto = Crypto(
SharedPrefsBackedKeyChain(context),
SystemNativeCryptoLibrary())
try {
val json = LoganSquare.serialize(user)
val cipherArray = crypto.encrypt(json.toByteArray(), Entity("user"))
val cipherString = Base64.encodeToString(cipherArray, Base64.NO_WRAP)
sharedpreferences.edit().putString("userObject", cipherString).apply()
} catch (e: KeyChainException) {
e.printStackTrace()
} catch (e: CryptoInitializationException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun getUser(context: Context): User? {
val sharedpreferences = context.getSharedPreferences("userPrefs", Context.MODE_PRIVATE)
val crypto = Crypto(
SharedPrefsBackedKeyChain(context),
SystemNativeCryptoLibrary())
try {
val plainArray = Base64.decode(sharedpreferences.getString("userObject", ""), Base64.DEFAULT)
val cipherJsonArray = crypto.decrypt(plainArray, Entity("user"))
val cipherJson = String(cipherJsonArray)
return LoganSquare.parse(cipherJson, User::class.java)
} catch (e: KeyChainException) {
e.printStackTrace()
} catch (e: CryptoInitializationException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} catch (noUser: ArrayIndexOutOfBoundsException) {
return null
}
return null
}
fun deleteUser(context: Context) {
val sharedpreferences = context.getSharedPreferences("userPrefs", Context.MODE_PRIVATE)
sharedpreferences.edit().remove("userObject").apply()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment