Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DecryptingPropertiesListener
- implements ApplicationListener<ContextRefreshedEvent>, Ordered {
- public static final String PREFIX_KEY = "{cipher}";
- private String prefix;
- private Encrypter encrypter = Encrypter.defaultInstance();
- @Override
- public void onApplicationEvent(ContextRefreshedEvent event ) {
- Environment environment = event.getApplicationContext().getEnvironment();
- prefix = environment.getProperty(PREFIX_KEY, "{encrypted}");
- final MutablePropertySources propertySources = ((ConfigurableEnvironment) environment).getPropertySources();
- Set<String> encryptedKeys = getKeysOfEncryptedPropertyValues(environment, propertySources);
- addDecryptedValues(environment, propertySources, encryptedKeys);
- }
- private Set<String> getKeysOfEncryptedPropertyValues(Environment environment, MutablePropertySources propertySources) {
- return streamFromIterator(propertySources.iterator())
- .filter(EnumerablePropertySource.class::isInstance)
- .map(EnumerablePropertySource.class::cast)
- .flatMap(source -> asList(source.getPropertyNames()).stream())
- .filter(this::isNotEncryptionConfigProperty)
- .filter(key -> isEncrypted(environment.getProperty(key)))
- .collect(toSet());
- }
- private boolean isNotEncryptionConfigProperty(String key) {
- return !PREFIX_KEY.equals(key);
- }
- private Stream<PropertySource<?>> streamFromIterator(Iterator<PropertySource<?>> iterator) {
- Iterable<PropertySource<?>> iterable = () -> iterator;
- return StreamSupport.stream(iterable.spliterator(), false);
- }
- private void addDecryptedValues(Environment environment, MutablePropertySources propertySources, Set<String> encryptedKeys) {
- Map<String, Object> decryptedProperties = encryptedKeys.stream()
- .collect(toMap(
- key -> key,
- key -> decryptPropertyValue(environment.getProperty(key))));
- propertySources.addFirst(new MapPropertySource("decryptedValues", decryptedProperties));
- }
- private String decryptPropertyValue(String encryptedPropertyValue) {
- try {
- return encrypter.decryptIfEncrypted(encryptedPropertyValue);
- }
- catch (EncryptionException e) {
- throw new RuntimeException("Unable to decrypt property value '" + encryptedPropertyValue + "'", e);
- }
- }
- private boolean isEncrypted(Object propertyValue) {
- return propertyValue != null && propertyValue instanceof String && ((String)propertyValue).startsWith(prefix);
- }
- @Override
- public int getOrder() {
- return Ordered.LOWEST_PRECEDENCE;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement