All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ulisesbocchio.jasyptmavenplugin.mojo.AbstractReencryptMojo Maven / Gradle / Ivy

There is a newer version: 3.0.5
Show newest version
package com.ulisesbocchio.jasyptmavenplugin.mojo;

import com.ulisesbocchio.jasyptmavenplugin.encrypt.EncryptionService;
import com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder;
import com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.plugin.MojoExecutionException;
import org.jasypt.encryption.StringEncryptor;

import java.nio.file.Path;
import java.util.function.Consumer;

/**
 * Reencrypts a file using an old configuration to decrypt and then a new configuration to encrypt.
 */
@Slf4j
public abstract class AbstractReencryptMojo extends AbstractFileJasyptMojo {
    protected void run(final EncryptionService newService, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException {
        String decryptedContents = decrypt(path, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);

        log.info("Re-encrypting file " + path);
        try {
            String encryptedContents = newService.encrypt(decryptedContents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
            FileService.write(path, encryptedContents);
        } catch (Exception e) {
            throw new MojoExecutionException("Error Re-encrypting: " + e.getMessage(), e);
        }
    }

    private String decrypt(final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException {
        log.info("Decrypting file " + path);
        try {
            String contents = FileService.read(path);
            return getOldEncryptionService().decrypt(contents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
        } catch (Exception e) {
            throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e);
        }
    }

    private EncryptionService getOldEncryptionService() {
        JasyptEncryptorConfigurationProperties properties = new JasyptEncryptorConfigurationProperties();

        configure(properties);

        StringEncryptor encryptor = new StringEncryptorBuilder(properties, "jasypt.plugin.old").build();
        return new EncryptionService(encryptor);
    }

    protected abstract void configure(JasyptEncryptorConfigurationProperties properties);

    protected  void setIfNotNull(Consumer setter, T value) {
        if (value != null) {
            setter.accept(value);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy