@user944849 got me started in the right direction, and here's the solution.
If you're using Maven 2, you need to add the following dependency to your mojo:
<dependency>
<groupId>org.sonatype.plexus</groupId>
<artifactId>plexus-sec-dispatcher</artifactId>
<version>1.4</version>
<scope>compile</scope>
</dependency>
And put the following in src/main/resources/META-INF/plexus/components.xml
:
<?xml version="1.0" encoding="utf-8" ?>
<component-set>
<components>
<component>
<role>org.sonatype.plexus.components.sec.dispatcher.SecDispatcher</role>
<role-hint>mng-4384</role-hint>
<implementation>org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher</implementation>
<requirements>
<requirement>
<role>org.sonatype.plexus.components.cipher.PlexusCipher</role>
<role-hint>mng-4384</role-hint>
<field-name>_cipher</field-name>
</requirement>
</requirements>
<configuration>
<_configuration-file>~/.m2/settings-security.xml</_configuration-file>
</configuration>
</component>
<component>
<role>org.sonatype.plexus.components.cipher.PlexusCipher</role>
<role-hint>mng-4384</role-hint>
<implementation>org.sonatype.plexus.components.cipher.DefaultPlexusCipher</implementation>
</component>
</components>
</component-set>
Then in your Mojo, get the password as an ordinary property, and a SecDispatcher
as a component with the same roleHint
. The decrypt
method on the String
will return the string itself if it's not a Maven encrypted string.
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException;
/**
* @goal echopass
*
* @phase process-sources
*/
public class MyMojo extends AbstractMojo {
/**
* The password
* @parameter expression="${password}"
*/
private String password;
/**
* Plexus component for the SecDispatcher
* @component roleHint="mng-4384"
*/
private SecDispatcher secDispatcher;
private String decrypt(String input) {
try {
return secDispatcher.decrypt(input);
} catch (SecDispatcherException sde) {
getLog().warn(sde.getMessage());
return input;
}
}
public void execute() throws MojoExecutionException {
String s = decrypt(password);
getLog().info("The password is " + s);
}
}
The string can be in a property in settings.xml
, in a Profile, or you can even pass an encrypted string as a system property on the command-line.
References: