@ -22,6 +22,89 @@
package org.mosad.seil0.projectlaogai.controller.login
class LoginController {
// TODO implement
import android.content.Context
import android.content.SharedPreferences
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import org.mosad.seil0.projectlaogai.R
object LoginController {
var email = " "
internal set
/ * *
* initially load the users email
* /
fun load ( context : Context ) {
with ( getEncryptedPreferences ( context ) ) {
email = this ?. getString (
context . getString ( R . string . save _key _user _email ) ,
context . getString ( R . string . sample _user )
) . toString ( )
}
}
/ * *
* save user email and password to encrypted preference
* /
fun saveCredentials ( email : String , password : String , context : Context ) {
this . email = email
with ( getEncryptedPreferences ( context ) ?. edit ( ) ) {
this ?. putString ( context . getString ( R . string . save _key _user _email ) , email )
this ?. putString ( context . getString ( R . string . save _key _user _password ) , password )
this ?. apply ( )
}
}
/ * *
* read user email and password from encrypted preference
* /
fun readCredentials ( context : Context ) : Pair < String , String > {
return with ( getEncryptedPreferences ( context ) ) {
email = this ?. getString ( context . getString ( R . string . save _key _user _email ) , " " ) . toString ( )
Pair (
this ?. getString ( context . getString ( R . string . save _key _user _email ) , " " ) . toString ( ) ,
this ?. getString ( context . getString ( R . string . save _key _user _password ) , " " ) . toString ( )
)
}
}
/ * *
* create a encrypted shared preference
* /
private fun getEncryptedPreferences ( context : Context ) : SharedPreferences ? {
return try {
val spec = KeyGenParameterSpec . Builder ( MasterKey . DEFAULT _MASTER _KEY _ALIAS ,
KeyProperties . PURPOSE _ENCRYPT or KeyProperties . PURPOSE _DECRYPT )
. setBlockModes ( KeyProperties . BLOCK _MODE _GCM )
. setEncryptionPaddings ( KeyProperties . ENCRYPTION _PADDING _NONE )
. setKeySize ( MasterKey . DEFAULT _AES _GCM _MASTER _KEY _SIZE )
. build ( )
val masterKey = MasterKey . Builder ( context )
. setKeyGenParameterSpec ( spec )
. build ( )
EncryptedSharedPreferences . create (
context ,
context . getString ( R . string . encrypted _preference _file _key ) ,
masterKey ,
EncryptedSharedPreferences . PrefKeyEncryptionScheme . AES256 _SIV ,
EncryptedSharedPreferences . PrefValueEncryptionScheme . AES256 _GCM
)
} catch ( ex : Exception ) {
Log . e ( javaClass . name , " Could not create encrypted shared preference. " , ex )
null
}
}
}