Code Monkey home page Code Monkey logo

Comments (8)

lviggiano avatar lviggiano commented on June 3, 2024

👍 That is indeed very interesting. It happened many times I have deployed application in shared environment and some sensitive information was exposed in the configuration files. And that was not desirable, of course.

I would like to add this feature.

from owner.

lviggiano avatar lviggiano commented on June 3, 2024

@jpurnomosidi I think that it should be possible for the user to implement some encryption using the @ConverterClass annotation.

For instance:

import org.aeonbits.owner.Config;
import org.aeonbits.owner.ConfigFactory;
import org.aeonbits.owner.Converter;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * To encrypt the password:
 *   System.out.println(new BASE64Encoder().encode(xor("tiger".getBytes(), "secret".getBytes())));
 */

public class EncryptedPropertiesExample {

    interface EncryptedConfiguration extends Config {
        @ConverterClass(DecryptConverter.class)
        @DefaultValue("BwwEFxc=")
        String scottPassword();
    }

    public static class DecryptConverter implements Converter {
        public Object convert(Method method, String input) {
            try {
                String key = System.getProperty("example.encryption.key");
                return new String(xor(new BASE64Decoder().decodeBuffer(input), key.getBytes()));
            } catch (IOException e) {
                throw new UnsupportedOperationException(e);
            }
        }
    }

    public static void main(String[] args) {
        System.setProperty("example.encryption.key", "secret");
        EncryptedConfiguration example = ConfigFactory.create(EncryptedConfiguration.class);
        System.out.println(example.scottPassword());
    }

    private static byte[] xor(final byte[] input, final byte[] secret) {
        final byte[] output = new byte[input.length];
        if (secret.length == 0) {
            throw new IllegalArgumentException("empty encryption key");
        }
        int spos = 0;
        for (int pos = 0; pos < input.length; ++pos) {
            output[pos] = (byte) (input[pos] ^ secret[spos]);
            ++spos;
            if (spos >= secret.length) {
                spos = 0;
            }
        }
        return output;
    }
}

When you run the above code, it will print tiger.

The above code runs fine with version 1.0.5-SNAPSHOT (on master branch), but possibly it doesn't work with version 1.0.4.1 and prior (all released versions).

If you need this to work, I can backport a fix I made for 1.0.5-SNAPSHOT into 1.0.4 branch and release a bugfix release 1.0.4.2 so you can exploit this solution.

Let me know.

By the way, I would like to implement some strong property encryption mechanism inside owner itself; in the meantime, this solution can possibly fix urgencies?

from owner.

jpurnomosidi avatar jpurnomosidi commented on June 3, 2024

1.0.4.2 is ok. Btw, it's better not to use Sun base64 encoder/decoder (http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html). Better use apache common codec or javax.xml.bind.DatatypeConverter.

See http://stackoverflow.com/questions/5549464/import-sun-misc-base64encoder-got-error-in-eclipse

from owner.

lviggiano avatar lviggiano commented on June 3, 2024

I know, that was just for an example ;)

from owner.

lviggiano avatar lviggiano commented on June 3, 2024

I removed the sun base64 and added commons-codec as test dependency. I will implement this feature more appropriately in the next versions. Today I released version 1.0.5 so you can use the solution I proposed as example if you update to version 1.0.5.

At the moment of writing, version 1.0.5 is not yet on maven central repository yet, but it should be there soon.

from owner.

rajatvig avatar rajatvig commented on June 3, 2024
public static class EncryptedValueConverter implements Converter<String> {
        @Override
        public String convert(Method method, String input) {
            return (PropertyValueEncryptionUtils.isEncryptedValue(input) ? PropertyValueEncryptionUtils.decrypt(input, getEncryptor()) : input);
        }

    private StringEncryptor getEncryptor() {
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        config.setAlgorithm("PBEWITHMD5ANDDES");
        config.setPasswordEnvName("PASSWORD");

        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        standardPBEStringEncryptor.setConfig(config);
        return standardPBEStringEncryptor;
    }
}

The code is roughly illustrative of how we've used it with Jaspyt.
Maybe providing an annotation to provide the Encyptor will be nice.

from owner.

lviggiano avatar lviggiano commented on June 3, 2024

Thanks @rajatvig for the example.

from owner.

rrialq avatar rrialq commented on June 3, 2024

@lviggiano:
I have a owner version which implements this feature, I will do a pull request as soon as possible, after ending my tests, if you think this is the right way. The implementation doesn't need an external library. An example of a configuration with these feature:

    @DecrypterManagerClass(SampleDecrypter.class)
    public interface SampleConfig extends Config {
        @Key("password")
        @EncryptedKey
        @DefaultValue("LEXKJVu5XG/0fSgAROlfSG+a5TfXz4HeJ/tbjUuM8cg=")
        String password();

        @Key("myapp.username")
        String username;

@DecrypterManagerClass is a simple annotation to set the class that decrypts all of the passwords in this configuration.
@ENCRYPTEDKEY is the annotation to mark a property as encrypted. In previous example only password property will be decrypted by the SampleDecrypter.

The following code is implemented in the new code, and avoids the commons-codec library. Following is an example about using javax.crypto:

import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import javax.xml.bind.DatatypeConverter;

public class AESEncryption {
    public static final String ALGORITHM = "AES";

    private final String encoding;
    private final byte[] keyValue;

    public String getAlgorithm() {
        return AESEncryption.ALGORITHM;
    }

    public AESEncryption( String keyValue )
    throws UnsupportedEncodingException {
        this ( keyValue, "UTF-8" );
    }

    public AESEncryption( String keyValue, String encoding )
    throws UnsupportedEncodingException {
        this.encoding = encoding;
        this.keyValue = keyValue.getBytes( encoding );
    }

    public String encrypt(String plainData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal( plainData.getBytes( this.encoding ) );
        String encryptedValue = DatatypeConverter.printBase64Binary( encVal );
        return encryptedValue;
    }

    public String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance( ALGORITHM );
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = DatatypeConverter.parseBase64Binary( encryptedData );
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue, this.encoding );
        return decryptedValue;
    }

    private Key generateKey() throws Exception {
        return new SecretKeySpec( this.keyValue, this.getAlgorithm() );
    }
}

A simple test:

import java.io.UnsupportedEncodingException;
import org.junit.Assert;
import org.junit.Test;

public class AESEncryptionTestCase {
    @Test
    public void encriptionDecriptionTest()
    throws UnsupportedEncodingException, Exception {
        String cipherKey = "ABCDEFGH12345678";
        String expectedValue = "This is a decoded value";
        AESEncryption aes = new AESEncryption( cipherKey );
        String encriptedValue = aes.encrypt( expectedValue );
        System.out.println( "Encripted=" + encriptedValue );
        String decriptedValue = aes.decrypt( encriptedValue );
        System.out.println( "Decripted=" + decriptedValue);
        Assert.assertEquals("The decripted value is not the same as original value", expectedValue, decriptedValue);
    }
}

from owner.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.