Spring Mongo模板密码加密

时间:2013-08-22 01:36:22

标签: java spring mongodb

我正在为Mongo数据库服务器使用spring mongo模板,我需要加密属性文件中的密码并在Mongo模板中解密

我正在使用UserCredentials类传递用户名&密码。

任何人都可以帮助如何覆盖此类以解密加密密码并传递到Mongo模板

<bean id="simpleJdbcTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo"/>
<constructor-arg name="databaseName" value="mooadmin"/>
<constructor-arg name="userCredentials" ref="mongoCredentials"/>
</bean>

<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="${mongo.server}"/>
<property name="port" value="${mongo.port}"/>
</bean>

<bean id="mongoCredentials" 
  class="org.springframework.data.authentication.UserCredentials">
     <constructor-arg name="username" value="${mongo.username}" />
     <constructor-arg name="password" value="${mongo.password}" />
</bean>

1 个答案:

答案 0 :(得分:2)

请参阅此处了解加密/解密机制:Java 256-bit AES Password-Based Encryption

假设您已经弄清楚如何根据上面的链接解密字符串,您可以简单地覆盖UserCredentials类的密码getter

package com.mycompany;

// imports..

public class UserCredentials extends org.springframework.data.authentication.UserCredentials {

  private String decrypt(String encryptedStr) {
    // your decryption code goes here...
  }

  @Override
  public String getPassword() {
     return decrypt(super.getPassword());
  }
}

将加密密码放在属性文件中,并在spring xml配置文件中设置UserCredentials子类:

<bean id="mongoCredentials" 
  class="com.mycompany.UserCredentials">
     <constructor-arg name="username" value="${mongo.username}" />
     <constructor-arg name="password" value="${mongo.encryptedPassword}" />
</bean>