russhwolf / multiplatform-settings

A Kotlin Multiplatform library for saving simple key-value data
Apache License 2.0
1.7k stars 67 forks source link

Encrypted preferences Question #189

Closed mpierucci closed 8 months ago

mpierucci commented 8 months ago

If I understood correctly, one way to provide encrypted preferences in android would be with a custom factory and wrapping the encrypted preferences that androidx provide:

@Inject
class EncryptedPreferenceFactory(
    private val context: Application
) : Settings.Factory {

    override fun create(name: String?): Settings {
        checkNotNull(name) { "Settings Name cannot be null" }
        val masterKey: MasterKey = MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build()
        val sharedPreferences = EncryptedSharedPreferences.create(
            context,
            name,
            masterKey,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )

        return SharedPreferencesSettings(sharedPreferences)
    }
}

With this in mind you can then expose this factory throgh DI ( Koltin inject example)

typealias EncryptedFactory = Settings.Factory\

   @Provides
    fun provideEncryptedFactory(
        application: Application
    ): EncryptedFactory = EncryptedPreferenceFactory(application)

But if you want to support iOS for example, since Encryption is already supported you've endup creating something like:

@OptIn(ExperimentalSettingsImplementation::class)
@Inject
class EncryptedPreferenceFactory : Settings.Factory {

    override fun create(name: String?): Settings {
        checkNotNull(name) { "Settings Name cannot be null" }
        return KeychainSettings(name)
    }
}

So Assuming Im not missing something very obvious would'nt be convinient for the library to provide a iOS KeyChainsSettingsFactory out of the box?

russhwolf commented 8 months ago

KeychainSettings.Factory already exists.

mpierucci commented 8 months ago

Wow I really missed this one, thanks! Closing this now