Using encoded password for the datasource used in spring applicationContext.xml

后端 未结 5 999
野性不改
野性不改 2021-01-31 18:53

I want to keep encoded password in my below mentioned springApplicationContext.xml

Is there any way to achieve this?

presently I have configured all properties

5条回答
  •  伪装坚强ぢ
    2021-01-31 19:37

    Its might be funny that I am answering to my own question. but still I just wanted to tell my solution, others who might have faced same kind of issue..

    for simplicity I have used BASE64Encoder & BASE64Decoder. later I will modify my code to use a secure/better encryption/decryption algorithm.

    I have encoded my database password(ex: root for my case) by using the below code:

    private String encode(String str) {
            BASE64Encoder encoder = new BASE64Encoder();
            str = new String(encoder.encodeBuffer(str.getBytes()));
            return str;
        }
    

    and placed the encoded password in my database.properties file like below:

    before

    db.driverClassName=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://localhost/myDB
    db.username=root
    db.password=root
    

    after

    db.driverClassName=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://localhost/myDB
    db.username=root
    db.password=cm9vdA==  (Note: encoded 'root' by using BASE64Encoder)
    

    Now I have written a wrapper class for org.apache.commons.dbcp.BasicDataSource and overridden setPassword() method:

    import java.io.IOException;
    import org.apache.commons.dbcp.BasicDataSource;
    import sun.misc.BASE64Decoder;
    
    public class MyCustomBasicDataSource extends BasicDataSource{
    
        public CustomBasicDataSource() {
            super();
        }
    
        public synchronized void setPassword(String encodedPassword){
            this.password = decode(encodedPassword);
        }
    
        private String decode(String password) {
            BASE64Decoder decoder = new BASE64Decoder();
            String decodedPassword = null;
            try {
                decodedPassword = new String(decoder.decodeBuffer(password));
            } catch (IOException e) {
                e.printStackTrace();
            }       
            return decodedPassword;
        }
    }
    

    This way I am decoding(BASE64Decoder) the encoded password provided in database.properties

    and also modified the class attribute of my dataSource bean mentioned in springApplicationContext.xml file.

    
        ${db.driverClassName}
        ${db.url}
        ${db.username}
        ${db.password}
    

    Thanks.

提交回复
热议问题