Skip to content

Instantly share code, notes, and snippets.

@MAshhal
Created August 22, 2024 06:19
Show Gist options
  • Select an option

  • Save MAshhal/636be4a3292f353f21547d02fdaef096 to your computer and use it in GitHub Desktop.

Select an option

Save MAshhal/636be4a3292f353f21547d02fdaef096 to your computer and use it in GitHub Desktop.

Hiding Secrets / API keys in *.properties files

Note

If you are using convention plugin for your project, solution at the bottom.

Tip

I would recommend creating another secrets.properties file just for ease of use, but this will work for any .properties file.

I will create another secrets.properties file in the project's root directory.

  1. Add your secrets in the file
secret_key=<value>
api_key=<value>
  1. Inside build.gradle.kts file (i.e. inside the android block) you can load the key-value properties from the .properties file and access them as follows:
android { ...

    defaultConfig { ...

      val secretsFile = rootProject.file("secrets.properties")
      val properties = Properties()
      properties.load(secretsFile.inputStream())
    
      // Return an empty string in case of property being null
      val apiKey = properties.getProperty("api_key") ?: ""
      
      // For accessing the property using BuildConfig
      buildConfigField(
          type = "String",
          name = "API_KEY",
          value = apiKey
      )
    }
    // ...
}
  1. Sync the project and access the keys through the BuildConfig class in your source code.
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        val apiKey = BuildConfig.API_KEY
        
        ...
}

- Setting buildConfigField in convention plugins.

/**
 * Created using Android Studio
 * User: ashal
 * Date: 8/22/2024
 * Time: 11:16 AM
 */

class AndroidApplicationConventionPlugin : Plugin<Project> {
    override fun apply(target: Project) {
      with(target) {
        ....
        
            extensions.configure<ApplicationExtension> {
                configureKotlinAndroid(this)
                defaultConfig.targetSdk = libs.versions.targetSdk.get().toInt()

                
                val secretsFile = rootProject.file("secrets.properties")
                val properties = Properties()
                properties.load(secretsFile.inputStream())
                
                defaultConfig.buildConfigField(
                    type = "String",
                    name = "API_KEY",
                    value = properties.loadProperty("api_key") ?: ""
                )

            }
        }
    }
}
@rishav2404
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment