Git Product home page Git Product logo

encrypted-datastore's Introduction

Encrypted DataStore

Version License

Extensions to store DataStore in EncryptedFile.

Warning

This tiny library will be maintained until an official solution for DataStore encryption will be released by Google. Vote for this feature on issue tracker: b/167697691


Installation

Add the dependency:

repositories {
    mavenCentral()
    google()
}

dependencies {
    implementation("io.github.osipxd:security-crypto-datastore:1.0.0")
    // Or, if you want to use Preferences DataStore:
    implementation("io.github.osipxd:security-crypto-datastore-preferences:1.0.0")
}

Dependencies:

Usage

To create encrypted DataStore, just use method encryptedDataStore instead of dataStore to create delegate:

// At the top level of your Kotlin file:
val Context.settingsDataStore: DataStore<Settings> by encryptedDataStore(
    fileName = "settings.pb",
    serializer = SettingsSerializer
)
Or, if you want full control over EncryptedFile creation
val settingsDataStore: DataStore<Settings> = DataStoreFactory.createEncrypted(SettingsSerializer) {
    EncryptedFile.Builder(
        context.dataStoreFile("settings.pb"),
        context,
        MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()
}

Similarly, you can create Preferences DataStore:

// At the top level of your Kotlin file:
val Context.dataStore by encryptedPreferencesDataStore(name = "settings")
Or, if you want full control over EncryptedFile creation
val dataStore: DataStore<Preferences> = PreferenceDataStoreFactory.createEncrypted {
    EncryptedFile.Builder(
        context.preferencesDataStoreFile("settings"),
        context,
        MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()
}

Then you can use the created encrypted DataStore just like simple DataDtore. Look at the DataStore docs for usage guide and examples.

Migration

Migrate from factory to delegate

If you have the following code:

val dataStore = DataStoreFactory.createEncrypted(serializer) {
    EncryptedFile.Builder(
        context.dataStoreFile("filename"),
        context,
        MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()
}

You can simplify it using delegate for DataStore creation.

// 1. Move the field to top level of you Kotlin file and turn it to an extension on Context
// 2. Replace `DataStoreFactory.createEncrypted` with `encryptedDataStore`
val Context.dataStore by encryptedDataStore(
    fileName = "filename", // Keep file the same
    serializer = serializer,
)

Note

This only will be interchangeable if you used context.dataStoreFile(...) to create datastore file. In case you have custom logic for master key creation, pass the created master key as a parameter masterKey to the delegate.

Migrate from encrypted-datastore to security-crypto-datastore

Change the dependency in build script:

 dependencies {
-    implementation("io.github.osipxd:encrypted-datastore:...")
+    implementation("io.github.osipxd:security-crypto-datastore:...")
 }

New library uses StreamingAead instead of Aead under the hood, so to not lose the previously encrypted data you should specify fallbackAead:

// This AEAD was used to encrypt DataStore previously, we will use it as fallback
val aead = AndroidKeysetManager.Builder()
    .withSharedPref(context, "master_keyset", "master_key_preference")
    .withKeyTemplate(KeyTemplates.get("AES256_GCM"))
    .withMasterKeyUri("android-keystore://master_key")
    .build()
    .keysetHandle
    .getPrimitive(Aead::class.java)

The old code to create DataStore was looking like this:

val dataStore = DataStoreFactory.create(serializer.encrypted(aead)) {
    context.dataStoreFile("filename")
}

The new code will look like this:

// At the top level of your Kotlin file:
val Context.dataStore by encryptedDataStore(
    fileName = "filename", // Keep file the same
    serializer = serializer,
    encryptionOptions = {
        // Specify fallback Aead to make it possible to decrypt data encrypted with it
        fallbackAead = aead
    }
)
Or, if you want full control over EncryptedFile creation
val dataStore = DataStoreFactory.createEncrypted(
    serializer = serializer,
    encryptionOptions = { fallbackAead = aead }
) {
    EncryptedFile.Builder(
        context.dataStoreFile("filename"), // Keep file the same
        context,
        MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()
}

Thanks

  • Artem Kulakov (Fi5t), for his example of DataStore encryption.
  • Gods of Kotlin, for posibility to hack internal visibility modifier

License

MIT

encrypted-datastore's People

Contributors

osipxd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

encrypted-datastore's Issues

Build with AGP 8.0 leads to crashes in runtime

If I build the library with AGP 8.0+, I get a runtime exception:

java.lang.NoClassDefFoundError: Failed resolution of: Lio/github/osipxd/datastore/encrypted/PreferenceDataStoreHack;
    at io.github.osipxd.datastore.encrypted.EncryptedPreferenceDataStoreKt.(EncryptedPreferenceDataStore.kt:52)
    at io.github.osipxd.datastore.encrypted.EncryptedPreferenceDataStoreKt.getPreferencesSerializer(EncryptedPreferenceDataStore.kt:52)
Caused by: java.lang.ClassNotFoundException: Didn't find class "io.github.osipxd.datastore.encrypted.PreferenceDataStoreHack" on path: DexPathList[[zip file "/data/app/~~xBo6035bH4FmFe4ueiv11g==/io.github.osipxd.security.datastore.preferences.test-llxPf-1rR2bKEpw4YiDFHA==/base.apk"],nativeLibraryDirectories=[/data/app/~~xBo6035bH4FmFe4ueiv11g==/io.github.osipxd.security.datastore.preferences.test-llxPf-1rR2bKEpw4YiDFHA==/lib/arm64, /system/lib64, /system_ext/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:259)

As a workaround, I'll stay on AGP 7.4.2 for now.

There was a similar bug in AGP 4.2, so maybe it's a regression: b/187353303

Signature/MAC verification failed

Hi,
Ran into this on a Samsung fold SM-F926U, running Android 13, and only on that phone. I am using the "androidx.security:security-crypto-ktx:1.1.0-alpha06" way of getting the preferences data store. I don't know if changing to the default way without ktx will help. I can't reliably test this since this is from a production build and like I said, no other phone experiences this.

Signature/MAC verification failed (internal Keystore code: -30 message: In KeystoreOperation::finish

Caused by:
    0: In finish: KeyMint::finish failed.
    1: Error::Km(ErrorCode(-30)))

Preferences DataStore: `preferences_pb` filename extension requirement and migration

I am trying to migrate an existing encrypted Preferences DataStore implementation from encrypted-datastore:1.0.0-alpha02 to security-crypto-datastore-preferences:1.0.0-alpha04, but the original preferences filename does not have a .preferences_pb extension, as that was never a requirement before.

When I follow the migration steps, I get an exception at runtime:

java.lang.IllegalStateException: File extension for file: /data/user/0/com.package/files/datastore/session does not match required extension for Preferences file: preferences_pb

How should I migrate users to the newer StreamingAead implementation without losing the previously Aead encrypted data in this original file?

InvalidProtocolBufferException (Protocol message contained an invalid tag (zero))

app crash due to "androidx.security:security-crypto" that u internally use . i know this crash something related to google security-crypto library . but when I figure out for a solution I found many developers recommend to downgrade to ecurity-crypto:1.1.0-alpha01 , so does yr library support alpha versions or if u have any idea to solve this ?

thanks

error log...

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.app, PID: 2511
    java.lang.RuntimeException: Unable to create application com.app.MainApplication: com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6790)
        at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2134)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7898)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
     Caused by: com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
        at com.google.crypto.tink.shaded.protobuf.ArrayDecoders.decodeUnknownField(ArrayDecoders.java:1036)
        at com.google.crypto.tink.shaded.protobuf.ArrayDecoders.decodeUnknownField(ArrayDecoders.java:1028)
        at com.google.crypto.tink.shaded.protobuf.ArrayDecoders.decodeUnknownField(ArrayDecoders.java:1028)
        at com.google.crypto.tink.shaded.protobuf.ArrayDecoders.decodeUnknownField(ArrayDecoders.java:1028)
        at com.google.crypto.tink.shaded.protobuf.MessageSchema.parseProto3Message(MessageSchema.java:5426)
        at com.google.crypto.tink.shaded.protobuf.MessageSchema.mergeFrom(MessageSchema.java:5442)
        at com.google.crypto.tink.shaded.protobuf.ArrayDecoders.decodeMessageField(ArrayDecoders.java:246)
        at com.google.crypto.tink.shaded.protobuf.ArrayDecoders.decodeMessageList(ArrayDecoders.java:704)
        at com.google.crypto.tink.shaded.protobuf.MessageSchema.parseProto3Message(MessageSchema.java:5373)
        at com.google.crypto.tink.shaded.protobuf.MessageSchema.mergeFrom(MessageSchema.java:5442)
        at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parsePartialFrom(GeneratedMessageLite.java:1567)
        at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parseFrom(GeneratedMessageLite.java:1680)
        at com.google.crypto.tink.proto.Keyset.parseFrom(Keyset.java:958)
        at com.google.crypto.tink.integration.android.SharedPrefKeysetReader.read(SharedPrefKeysetReader.java:84)
        at com.google.crypto.tink.CleartextKeysetHandle.read(CleartextKeysetHandle.java:61)
        at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.read(AndroidKeysetManager.java:332)
        at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewKeyset(AndroidKeysetManager.java:288)

Decrypting from stored protocol buffer file fails

After writing a protobuf file and reopening the app, reading the encrypted file fails with the following exception:

  Caused by: java.io.IOException: No matching key found for the ciphertext in the stream.
                 	at com.google.crypto.tink.streamingaead.InputStreamDecrypter.read(InputStreamDecrypter.java:176)
                 	at com.google.protobuf.CodedInputStream$StreamDecoder.read(CodedInputStream.java:2080)
                 	at com.google.protobuf.CodedInputStream$StreamDecoder.tryRefillBuffer(CodedInputStream.java:2831)
                 	at com.google.protobuf.CodedInputStream$StreamDecoder.isAtEnd(CodedInputStream.java:2754)
                 	at com.google.protobuf.CodedInputStream$StreamDecoder.readTag(CodedInputStream.java:2107)
                 	at com.google.protobuf.CodedInputStreamReader.getFieldNumber(CodedInputStreamReader.java:82)
                 	at com.google.protobuf.MessageSchema.mergeFromHelper(MessageSchema.java:3913)
                 	at com.google.protobuf.MessageSchema.mergeFrom(MessageSchema.java:3895)
                 	at com.google.protobuf.GeneratedMessageLite.parsePartialFrom(GeneratedMessageLite.java:1647)

I am using v1.0.0-alpha03 of the library.

Among other cases this type of error occurs when the outputstream the file is written to is not closed. This can be observed when using the regular EncryptedFile and not closing its outpur stream after write. Loading the file again fails with the same exception.

However looking at the datastore implementation... they make use if the file.use { ... } function which would indicate a close operation. Feedback is appreciated.

GeneralSecurityException: decryption failed

Fatal Exception: java.security.GeneralSecurityException: decryption failed
       at com.google.crypto.tink.aead.AeadWrapper$WrappedAead.decrypt(AeadWrapper.java:83)
       at io.github.osipxd.datastore.encrypted.EncryptedSerializer.readFrom(EncryptedSerializer.kt:16)
       at androidx.datastore.core.SingleProcessDataStore.readData(SingleProcessDataStore.kt:381)
       at androidx.datastore.core.SingleProcessDataStore.readDataOrHandleCorruption(SingleProcessDataStore.kt:359)
       at androidx.datastore.core.SingleProcessDataStore.readAndInit(SingleProcessDataStore.kt:322)
       at androidx.datastore.core.SingleProcessDataStore.readAndInitOrPropagateFailure(SingleProcessDataStore.kt:311)
       at androidx.datastore.core.SingleProcessDataStore.handleRead(SingleProcessDataStore.kt:261)
       at androidx.datastore.core.SingleProcessDataStore.access$getFile(SingleProcessDataStore.kt:76)
       at androidx.datastore.core.SingleProcessDataStore$actor$3.invokeSuspend(SingleProcessDataStore.kt:239)
       at androidx.datastore.core.SingleProcessDataStore$actor$3.invoke(SingleProcessDataStore.kt)
       at androidx.datastore.core.SingleProcessDataStore$actor$3.invoke(SingleProcessDataStore.kt)
       at androidx.datastore.core.SimpleActor$offer$2.invokeSuspend(SimpleActor.kt:122)
       at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
       at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
       at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
       at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
       at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)

Migration: Issue with reading `StreamingAeadWithFallback` input stream after fallback

Refs #14

I am trying to update an app that currently uses the encrypted Preferences DataStore implementation from encrypted-datastore:1.0.0-alpha02. The DataStore was setup as follows:

val aead = AndroidKeysetManager.Builder()
    .withSharedPref(context, "master_keyset", "master_key_preference")
    .withKeyTemplate(KeyTemplates.get("AES256_GCM"))
    .withMasterKeyUri("android-keystore://master_key")
    .build()
    .keysetHandle.getPrimitive(Aead::class.java)

PreferenceDataStoreFactory.createEncrypted(aead) {
    context.preferencesDataStoreFile(DATASTORE_NAME)
}

I have updated to security-crypto-datastore-preferences:1.0.0-alpha04 and changed the setup as follows to enable Aead fallback for existing users as follows:

val aead = AndroidKeysetManager.Builder()
    .withSharedPref(context, "master_keyset", "master_key_preference")
    .withKeyTemplate(KeyTemplates.get("AES256_GCM"))
    .withMasterKeyUri("android-keystore://master_key")
    .build()
    .keysetHandle.getPrimitive(Aead::class.java)
    
PreferenceDataStoreFactory.createEncrypted(
    encryptionOptions = { fallbackAead = aead }
) {
    EncryptedFile.Builder(
        context.preferencesDataStoreFile(DATASTORE_NAME), // Keep the same file
        context,
        MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()
}

When the app runs, no errors are raised, but any previously saved datastore key/values are not decrypting properly.

Debugging revealed that when the fallback lambda is executed to get the Aead decrypted FileInputStream, this method is always just returning the original encrypted FileInputStream, because its available() method returns 0 (suggesting that it has already been read).

internal fun Aead.newDecryptedStream(inputStream: InputStream): InputStream {
return if (inputStream.available() > 0) {
decrypt(inputStream.readBytes(), null).inputStream()
} else {
inputStream
}
}

I discovered I could fix the issue by adding a call to stream.close() in the fallback catch block just before stream is reassigned, so that the aborted StreamingAead input stream is closed first before reading from the fallback Aead stream.

override fun read(b: ByteArray, offset: Int, length: Int): Int {
return try {
stream.read(b, offset, length)
} catch (e: IOException) {
if (!e.isProbablyEncryptedWithAeadException()) throw e
stream = fallbackStream()
// Try to read again from the new delegate
stream.read(b, offset, length)
}
}

override fun read(b: ByteArray, offset: Int, length: Int): Int {
    return try {
        stream.read(b, offset, length)
    } catch (e: IOException) {
        if (!e.isProbablyEncryptedWithAeadException()) throw e
        stream.close()                                                       // <-- FIX
        stream = fallbackStream()
        // Try to read again from the new delegate
        stream.read(b, offset, length)
    }
}

I am honestly not sure why it is behaving this way. Perhaps there are some subtle differences between FileInputStream and the ByteArrayInputStream used in the tests?

Hopefully there is enough information here for you to reproduce the issue. Let me know if not.

Add Delegated Property

Just like the datastores offered by Android, can you add a delagate property based on the PreferenceDataStoreDelegate class.

We could create an encrypted datastore like this:

val Context.userDataStore: DataStore<UserData> by encryptedDataStore(
    name = "userData.pb",
    UserDataSerializer()
)

Here's an example of what that would look like:

/**
 * Creates a property delegate for a single process DataStore. This should only be called once
 * in a file (at the top level), and all usages of the DataStore should use a reference the same
 * Instance. The receiver type for the property delegate must be an instance of [Context].
 *
 * This should only be used from a single application in a single classloader in a single process.
 *
 * Example usage:
 * ```
 * val Context.myDataStore by preferencesDataStore("filename")
 *
 * class SomeClass(val context: Context) {
 *    suspend fun update() = context.myDataStore.edit {...}
 * }
 * ```
 *
 *
 * @param name The name of the preferences. The preferences will be stored in a file in the
 * "datastore/" subdirectory in the application context's files directory and is generated using
 * [preferencesDataStoreFile].
 * @param corruptionHandler The corruptionHandler is invoked if DataStore encounters a
 * [androidx.datastore.core.CorruptionException] when attempting to read data. CorruptionExceptions
 * are thrown by serializers when data can not be de-serialized.
 * @param produceMigrations produce the migrations. The ApplicationContext is passed in to these
 * callbacks as a parameter. DataMigrations are run before any access to data can occur. Each
 * producer and migration may be run more than once whether or not it already succeeded
 * (potentially because another migration failed or a write to disk failed.)
 * @param scope The scope in which IO operations and transform functions will execute.
 *
 * @return a property delegate that manages a datastore as a singleton.
 */
@Suppress("MissingJvmstatic")
fun <T> encryptedDataStore(
    name: String,
    serializer: Serializer<T>,
    corruptionHandler: ReplaceFileCorruptionHandler<T>? = null,
    produceMigrations: (Context) -> List<DataMigration<T>> = { listOf() },
    scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
): ReadOnlyProperty<Context, DataStore<T>> {
    return EncryptedDataStoreSingletonDelegate(
        name,
        serializer,
        corruptionHandler,
        produceMigrations,
        scope
    )
}

/**
 * Delegate class to manage Preferences DataStore as a singleton.
 */
internal class EncryptedDataStoreSingletonDelegate<T> internal constructor(
    private val name: String,
    private val serializer: Serializer<T>,
    private val corruptionHandler: ReplaceFileCorruptionHandler<T>?,
    private val produceMigrations: (Context) -> List<DataMigration<T>>,
    private val scope: CoroutineScope
) : ReadOnlyProperty<Context, DataStore<T>> {

    private val lock = Any()

    @GuardedBy("lock")
    @Volatile
    private var INSTANCE: DataStore<T>? = null

    /**
     * Gets the instance of the DataStore.
     *
     * @param thisRef must be an instance of [Context]
     * @param property not used
     */
    override fun getValue(thisRef: Context, property: KProperty<*>): DataStore<T> {
        return INSTANCE ?: synchronized(lock) {
            if (INSTANCE == null) {
                val applicationContext = thisRef.applicationContext

                INSTANCE = DataStoreFactory.createEncrypted(
                    serializer = serializer,
                    corruptionHandler = corruptionHandler,
                    migrations = produceMigrations(applicationContext),
                    scope = scope
                ) {
                    EncryptedFile.Builder(
                        applicationContext.dataStoreFile(name),
                        applicationContext,
                        MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
                        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
                    ).build()
                }
            }
            INSTANCE!!
        }
    }
}

Preferences DataStore crashes if obfuscation enabled

Stacktrace

Fatal Exception: java.lang.RuntimeException: Field value_ for e4.c not found. Known fields are [public int e4.c.e, public java.lang.Object e4.c.f, public static final e4.c e4.c.g, public static volatile g4.x$b e4.c.h]
       at androidx.datastore.preferences.protobuf.MessageSchema.reflectField(MessageSchema.java:608)
       at androidx.datastore.preferences.protobuf.MessageSchema.newSchemaForRawMessageInfo(MessageSchema.java:479)
       at androidx.datastore.preferences.protobuf.MessageSchema.newSchema(MessageSchema.java:221)
       at androidx.datastore.preferences.protobuf.ManifestSchemaFactory.newSchema(ManifestSchemaFactory.java:77)
       at androidx.datastore.preferences.protobuf.ManifestSchemaFactory.createSchema(ManifestSchemaFactory.java:71)
       at androidx.datastore.preferences.protobuf.Protobuf.schemaFor(Protobuf.java:93)
       at androidx.datastore.preferences.protobuf.Protobuf.schemaFor(Protobuf.java:107)
       at androidx.datastore.preferences.protobuf.GeneratedMessageLite.makeImmutable(GeneratedMessageLite.java:170)
       at androidx.datastore.preferences.protobuf.GeneratedMessageLite$Builder.buildPartial(GeneratedMessageLite.java:386)
       at androidx.datastore.preferences.protobuf.GeneratedMessageLite$Builder.build(GeneratedMessageLite.java:394)
       at androidx.datastore.preferences.core.PreferencesSerializer.getValueProto(PreferencesSerializer.kt:76)
       at androidx.datastore.preferences.core.PreferencesSerializer.writeTo(PreferencesSerializer.kt:63)
       at androidx.datastore.preferences.core.PreferencesSerializer.writeTo(PreferencesSerializer.kt:36)
       at io.github.osipxd.datastore.encrypted.EncryptedSerializer.writeTo(EncryptedSerializer.kt:23)
       at androidx.datastore.core.SingleProcessDataStore.writeData$datastore_core(SingleProcessDataStore.kt:426)
       at androidx.datastore.core.SingleProcessDataStore.transformAndWrite(SingleProcessDataStore.kt:410)
       at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$1.invokeSuspend(SingleProcessDataStore.kt:14)
       at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
       at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
       at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
       at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
       at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java:570)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)

Workarounds

  1. Add dependency androidx.datastore:datastore-preferences to build script
  2. Add proguard rules:
    -keepclassmembers class androidx.datastore.preferences.PreferencesProto$Value {
         private java.lang.Object value_;
         private int valueCase_;
    }
    
    -keepclassmembers class * extends androidx.datastore.preferences.protobuf.GeneratedMessageLite {
        <fields>;
    }

Getting Crash on App Launch

Caused by: java.security.KeyStoreException: the master key android-keystore://_androidx_security_master_key_ exists but is unusable
	at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewMasterKey(AndroidKeysetManager.java:276)
	at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:237)
	at androidx.security.crypto.EncryptedFile$Builder.build(EncryptedFile.java:172)
	at com.huru.datastore.di.DataStoreModule$getDataStore$1.invoke(DataStoreModule.kt:61)
	at com.huru.datastore.di.DataStoreModule$getDataStore$1.invoke(DataStoreModule.kt:55)
	at io.github.osipxd.security.crypto.EncryptedPreferenceDataStoreFactoryKt.createEncrypted(EncryptedPreferenceDataStoreFactory.kt:61)
	at io.github.osipxd.security.crypto.EncryptedPreferenceDataStoreFactoryKt.createEncrypted$default(EncryptedPreferenceDataStoreFactory.kt:48)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.