MixedEncrypt.java

package org.flasby.settings;

/**
 * extends the Encrypt behaviour to support mixed encrypted and plaintext property values.
 * Encrypted property values will be tagged with {CRYPT} to distinguish them from plaintext properties.
 * 
 * To store a plaintext property value simply call against the passed in SimpleSettings.
 * To store an encrypted property call against this class
 * Both plain and encrypted properties can be retrieved using get(). Encrypt will baulk at fetching a plaintext value.
 * 
 * @author steve
 *
 */
public class MixedEncrypt extends Encrypt {

	public static final String CRYPT_FLAG = "{CRYPT}";
	
	public MixedEncrypt( SimpleSettings settings, char[] passPhrase) throws Exception {
		super(settings, passPhrase);
	}

	public MixedEncrypt(final SimpleSettings settings, final char[] passPhrase,
			final byte[] salt, final String keyAlgorithm) throws Exception {
		super(settings, passPhrase, salt, keyAlgorithm);
	}
	
	@Override
	public String get(String name) {
		String value = super.getRaw(name);
		if ( value == null ) {
			return value;
		}
		if ( value.startsWith(CRYPT_FLAG) ) {
			return decrypt(value.substring(CRYPT_FLAG.length()));
		}
		return value;
	}
	
	public void add(String name, String value) {
		addRaw(name, CRYPT_FLAG+encrypt(value));
	}
}