How to connect to a database that requires password without exposing the password? How to connect to a database that requires password without exposing the password? database database

How to connect to a database that requires password without exposing the password?


The usual way this is done is to externalize the username/password to a property/config file which is read at runtime (whether or not you use native JDBC/JNDI/CDI/J2EE datasource/etc).

The file is protected via the O/S security by the sysadmins.

The O/S has better tools for protection than app code.


You can use jasypt for the encryption.And store the username and password to datasource.properties file.

public Connection getConnection() throws IOException{    try{        BasicTextEncryptor encryptor = new BasicTextEncryptor();        encryptor.setPassword("jasypt");        Properties props = new EncryptableProperties(encryptor);        props.load( this.getClass().getResourceAsStream("datasource.properties") );        String driver = props.getProperty("datasource.driver");        String url = props.getProperty("datasource.url");                String userName = props.getProperty("datasource.userName");                  String password = props.getProperty("datasource.password");        Class.forName(driver);        Connection conn = DriverManager.getConnection(url, userName, password);        conn.setAutoCommit(false);        return conn;    } catch(ClassNotFoundException e) {        e.printStackTrace();        return null;    } catch(SQLException e) {        e.printStackTrace();        return null;    }}


You should use a config file for this. use spring with JDBC to make your life easier!

http://www.youtube.com/watch?v=f-k823MZ02Q

Checkout the above awesome tutorial on the Spring framework and using JDBC. Watch all of his JDBC and spring tutorials.BTW, he covers how to store passwords in config files and wire beans etc.. Hope this helps.