Encrypt and Decrypt secret values (e.g. passwords) in properties files
The password in a property file should be encrypted by a secret key, stored somewhere save.
This secret file could be stored in:
“Secured Properties” can only be as save as the location of the secret key.
The Property file “myConfiguration.properties”:
mySecretPassword = test
The Java code:
// prepare custom config
final SecuredPropertiesConfig config = new SecuredPropertiesConfig()
.withSecretFile(new File("G:/mysecret.key"))
.initDefault();
// auto-encrypt values in the property-file:
SecuredProperties.encryptNonEncryptedValues(config,
new File("myConfiguration.properties"), // The Property File
"mySecretPassword"); // the property-key from "myConfiguration.properties"
// read encrypted values from the property-file
String secretValue = SecuredProperties.getSecretValue(config,
new File("myConfiguration.properties"), // The Property File
"mySecretPassword"); // the property-key from "myConfiguration.properties"
will return “test” as secretValue and automatically encrypt the value in the property file.
After the first run the Property file will looks similar to the following:
mySecretPassword = {wVtvW8lQrwCf8MA9sadwww==}
This encrypted password can now be read only in combination with the secret file “G:/mysecret.key”
It is also possible to encrypt multiple values at ones:
// custom configurations
final SecuredPropertiesConfig config = new SecuredPropertiesConfig()
.withSecretFile(new File("G:/mysecret.key"))
.initDefault();
Map secretValues = SecuredProperties.getSecretValues(config
new File("myConfiguration.properties"), // The Property File
"mySecretPassword", "anotherSecretPassword"); // the property-keys in "myConfiguration.properties"
The returned Map contains the decrypted passwords for the two keys “mySecretPassword”, “anotherSecretPassword”.
In some cases you don’t want encrypt/decrypt values from Properties Files.
This example shows how values from System Properties are encrypted/decrypted:
String systemPropPassword = System.getProperty(key);
if (SecuredProperties.isEncryptedPassword(systemPropPassword)) {
return SecuredProperties.decrypt(config, systemPropPassword);
} else if (StringUtils.isNotEmpty(systemPropPassword)) {
System.out.println(String.format("you could now use the following encrypted password: -D%s=%s", key,
SecuredProperties.encrypt(config, systemPropPassword)));
return systemPropPassword;
} else {
return null;
}
new SecuredPropertiesConfig() is a valid Configuration with following default behaviors:
All this configurations can be customized by the SecuredPropertiesConfig.java.
See: http://secured-properties.brabenetz.net/archiv/latest/configuration.html