Search code examples
androidencryptionandroidx

Unresolved reference: MasterKey


I am trying to follow examples given here: https://developer.android.com/topic/security/data

I have included the required libraries in my gradle:

implementation "androidx.security:security-crypto:1.0.0"

// For Identity Credential APIs
implementation "androidx.security:security-identity-credential:1.0.0-alpha02"

And yet when I try to use the code:

val mainKey = MasterKey.Builder(applicationContext)
    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
    .build()

I get unresolved reference: MasterKey error. Does the library have that class at all?

Thanks in advance.


Solution

  • Taking advantage of a hook in Jie Heng's response…

    The MasterKey API was added in the androidx.security package from the 1.1.0-alpha01 version of security-crypto (you can access the versions of this library here).

    If you apply the solution informed by Jie Heng, you will be successful.

    But if the Android project you're working on supports Android API 23 (aka Android Marshmallow or just Android 6)…

    something that should be accepted without problems, exactly as stated in the official documentation. Documentation showing how to use the EncryptedSharedPreferences and EncryptedFile APIs…

    if you go with minSdkVersion being 23, then you'll notice that the project won't even compile.

    That was my case!

    The project I work on supports from Android API level 23.

    So I applied the following update to AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="...">
    
        <uses-sdk tools:overrideLibrary="androidx.security.identity.credential" />
    ...
    

    And the project ran smoothly, including on Android API 23 (on AVD API 23).

    Note: another option is to use the MasterKeys API instead of MasterKey. But be aware that MasterKeys is deprecated.