1+ package com.el.yello.di
2+
3+ import android.content.Context
4+ import android.content.SharedPreferences
5+ import androidx.security.crypto.EncryptedSharedPreferences
6+ import androidx.security.crypto.MasterKey
7+ import com.el.yello.BuildConfig
8+ import com.example.data.local.qualifier.App
9+ import com.example.data.local.qualifier.User
10+ import dagger.Module
11+ import dagger.Provides
12+ import dagger.hilt.InstallIn
13+ import dagger.hilt.android.qualifiers.ApplicationContext
14+ import dagger.hilt.components.SingletonComponent
15+ import java.security.GeneralSecurityException
16+ import java.security.KeyStore
17+ import javax.inject.Singleton
18+
19+ @Module
20+ @InstallIn(SingletonComponent ::class )
21+ object DataStoreModule {
22+ private const val APP_PREFERENCES_NAME = " APP_DATA"
23+
24+ @Provides
25+ @Singleton
26+ @User
27+ fun provideUserPreferences (
28+ @ApplicationContext context : Context
29+ ): SharedPreferences = if (BuildConfig .DEBUG ) {
30+ context.getSharedPreferences(context.packageName, Context .MODE_PRIVATE )
31+ } else {
32+ try {
33+ createEncryptedSharedPreferences(context.packageName, context)
34+ } catch (e: GeneralSecurityException ) {
35+ deleteMasterKeyEntry()
36+ deleteExistingPref(context.packageName, context)
37+ createEncryptedSharedPreferences(context.packageName, context)
38+ }
39+ }
40+
41+ @Provides
42+ @Singleton
43+ @App
44+ fun provideAppPreferences (
45+ @ApplicationContext context : Context
46+ ): SharedPreferences = if (BuildConfig .DEBUG ) {
47+ context.getSharedPreferences(APP_PREFERENCES_NAME , Context .MODE_PRIVATE )
48+ } else {
49+ try {
50+ createEncryptedSharedPreferences(APP_PREFERENCES_NAME , context)
51+ } catch (e: GeneralSecurityException ) {
52+ deleteMasterKeyEntry()
53+ deleteExistingPref(APP_PREFERENCES_NAME , context)
54+ createEncryptedSharedPreferences(APP_PREFERENCES_NAME , context)
55+ }
56+ }
57+
58+ private fun deleteExistingPref (fileName : String , context : Context ) {
59+ context.deleteSharedPreferences(fileName)
60+ }
61+
62+ private fun deleteMasterKeyEntry () {
63+ KeyStore .getInstance(" AndroidKeyStore" ).apply {
64+ load(null )
65+ deleteEntry(MasterKey .DEFAULT_MASTER_KEY_ALIAS )
66+ }
67+ }
68+
69+ private fun createEncryptedSharedPreferences (
70+ fileName : String ,
71+ context : Context
72+ ): SharedPreferences {
73+ return EncryptedSharedPreferences .create(
74+ context,
75+ fileName,
76+ MasterKey .Builder (context, MasterKey .DEFAULT_MASTER_KEY_ALIAS )
77+ .setKeyScheme(MasterKey .KeyScheme .AES256_GCM )
78+ .build(),
79+ EncryptedSharedPreferences .PrefKeyEncryptionScheme .AES256_SIV ,
80+ EncryptedSharedPreferences .PrefValueEncryptionScheme .AES256_GCM
81+ )
82+ }
83+ }
0 commit comments