Avoiding plaintext passwords in gradle
Keychain Access can store passwords for gradle
Only for OSX
Security First
It is not recommended to store passwords in config files. A solution on OSX is to use the build in Keychain Access app, which conveniently may be accessed from the terminal.
In this example we will use it to store our passwords for the keystore used for signing Android apps.
This is not an original idea but just a slightly more verbose version of this stackoverflow answer.
Store Passwords in Keychain Access
- To open Keychain Access just press
space+cmd
and type keychain access. - Add a new password by pressing the plus sign
- As name you can put
android_keystore
or whatever you find suitable. Fill in your account name in account. Ultimately you fill in the password that you used when you created the key using keytool*.
* If you have different passwords for the store and the key you just repeat this whole process for the different passwords. If you don’t know how to generate keys, look at Generating a signing key.
Access passwords from terminal
Test your password by the following in terminal:
security find-generic-password -s android_keystore -w
You should get a prompt that asks you if you want to allow the password.
Access passwords in build.gradle
Add the following to the beginning of your build.gradle
def getPassword(String currentUser, String keyChain) {
def stdout = new ByteArrayOutputStream()
def stderr = new ByteArrayOutputStream()
exec {
commandLine 'security', '-q', 'find-generic-password', '-a', currentUser, '-s', keyChain, '-w'
standardOutput = stdout
errorOutput = stderr
ignoreExitValue true
}
//noinspection GroovyAssignabilityCheck
stdout.toString().trim()
}
Then when you are defining the passwords change it to the following:
// Add this line
def pass = getPassword("YOUR_USER_NAME","android_keystore")
...
android {
...
defaultConfig { ... }
signingConfigs {
release {
storeFile file(MYAPP_RELEASE_STORE_FILE)
storePassword pass // Change this
keyAlias MYAPP_RELEASE_KEY_ALIAS
keyPassword pass // Change this
}
}
buildTypes {
release {
...
signingConfig signingConfigs.release
}
}
}
...
Note: You have to set the file and alias in gradle.properties
as described here: Setting up gradle variables