SpringBoot下Druid密碼回調配置

使用druid-spring-boot-starter,配置自定義的數據庫密碼加密回調。
重寫com.alibaba.druid.util.DruidPasswordCallbacksetProperties方法。java

配置的密碼寫入密文

特別注意 spring.datasource.druid.password這個屬性必須存在,值空或者隨便寫算法

# 這個屬性必須存在,值空或者隨便寫
spring.datasource.druid.password=hello


# 自定義加密回調,特別注意,在AesDruidPasswordCallback中,讀取這些屬性值
spring.datasource.druid.password-callback-class-name=com.bbf.config.AesDruidPasswordCallback
# 在自定義的回調類中,須要讀pwd和key的值
spring.datasource.druid.connect-properties.pwd=Icdcxq3YHY56bSgFZOeLHY9eGB75RfReA4EvFFyNxsY=
spring.datasource.druid.connect-properties.key=pXR9pD4KhMGDlmVOQmJDBSJT4iGkXOUso2Fslo2dv3x

解密算法

這裏的AesUtil是本身定義的一種加密算法。實際中能夠換成其餘的算法。spring

import com.bbf.util.AesUtil;
import com.alibaba.druid.pool.DruidAbstractDataSource;
import com.alibaba.druid.util.DruidPasswordCallback;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 數據庫回調密碼解密
 * <p>在{@link DruidAbstractDataSource#createPhysicalConnection()}調用PasswordCallback方法時,
 * 會把getConnectProperties()的值放入,也就是spring.datasource.druid.connect-properties。
 * 不要與spring.datasource.druid.connection-properties混淆</p>
 *
 * @author BBF
 */
public class AesDruidPasswordCallback extends DruidPasswordCallback {

  private static final long serialVersionUID = 8636919602466752407L;
  private static final Logger LOGGER = LoggerFactory.getLogger(AesDruidPasswordCallback.class);

  @Override
  public void setProperties(Properties properties) {
    super.setProperties(properties);
    // 從druid的connectProperties中獲取自定義的配置信息
    String pwd = properties.getProperty("pwd");
    String key = properties.getProperty("key");
    char[] p = null;
    try {
      if (StringUtils.isNoneBlank(pwd, key)) {
        // 解密密碼
        String newPassword = AesUtil.cbcDecrypt(pwd, key);
        p = newPassword.toCharArray();
      }
    } catch (Exception ex) {
      LOGGER.error("[AesDruidPasswordCallback]解密失敗:{}", ex.getMessage(), ex);
    }
    super.setPassword(p);
  }
}

密碼加密測試類

/**
 * 數據庫加密測試類
 *
 * @author BBF
 */
public class AesDruidPasswordCallbackTest {

  private static final String PWD = "htdd";
  private static final String KEY = "pXR9pD4KhMGDlmVOQmJDBSJT4iGkXOUso2Fslo2dv3x";

  @Test
  public void encryptPassword() {
    try {
      String pwd = AesUtil.cbcEncrypt(PWD, KEY);
      System.out.println("預期密文:Icdcxq3YHY56bSgFZOeLHY9eGB75RfReA4EvFFyNxsY=");
      System.out.printf("計算密文:%s\n", pwd);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
相關文章
相關標籤/搜索