Spring实现加密数据库连接

一、加密工具类

下面的代码使用了apache的base64代替了sun公司的BASE64Decoder。依赖如下:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.8</version>
</dependency>
/**
 * DES加密工具类 <br>
 * 对称加密算法 : 加密和解密使用相同密钥的算法。
 * 
 * @author hkb <br>
 */
public class DESUtil {

    /** 日志记录对象 */
    private static final Logger LOGGER = LoggerFactory.getLogger(DESUtil.class);

    private static Key key;

    /** 密钥 */
    private static String SECRET_KEY = "secretKey";

    /** 必须设置编码 */
    private static String CHARSET = "UTF-8";

    /** 算法常量,这里使用DES */
    private static String ALGORITHM = "DES";

    static {
        try {
            // 生成DES算法对象
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            // 运用SHA1安全策略
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            // 设置密钥
            secureRandom.setSeed(SECRET_KEY.getBytes());
            // 初始化
            generator.init(secureRandom);
            // 生成密钥对象
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            LOGGER.error("生成密钥对象失败!");
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     * 
     * @param str
     * @return
     */
    public static String getEncryptString(String str) {
        Base64 base64 = new Base64();
        try {
            byte[] bytes = str.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(base64.encode(doFinal));
        } catch (Exception e) {
            LOGGER.error("加密失败!");
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     * 
     * @param str
     * @return
     */
    public static String getDecryptString(String str) {
        Base64 base64 = new Base64();
        try {
            byte[] bytes = base64.decode(str);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSET);
        } catch (Exception e) {
            LOGGER.error("解密失败!");
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 加密测试
        System.out.println(getEncryptString("root"));
        System.out.println(getEncryptString("123456"));

        // 解密测试
        System.out.println(getDecryptString("G5diwzl9+NY="));
        System.out.println(getDecryptString("DF29YY/dEVQ="));
    }

}

二、db.properties 配置文件内容

db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8
db.user=G5diwzl9+NY=
db.password=DF29YY/dEVQ=

三、配置文件解析工具类

该类继承自spring的PropertyPlaceholderConfigurer,代码中使用了apache的ObjectUtils来判断字符串。

/**
 * 继承自spring的PropertyPlaceholderConfigurer来扩展
 * 
 * @author hkb <br>
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    /** 需要解密的字段 */
    private String[] encryptPropNames = { "db.user", "db.password" };

    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        if (isEncryptProp(propertyName)) {
            // 解密
            String decryptValue = DESUtil.getDecryptString(propertyValue);
            return decryptValue;
        } else {
            return propertyValue;
        }
    }

    /**
     * 判断属性是否已加密
     * 
     * @param propertyName
     * @return
     */
    private boolean isEncryptProp(String propertyName) {
        for (String encryptpropertyName : encryptPropNames) {
            if (ObjectUtils.equals(encryptpropertyName, propertyName))
                return true;
        }
        return false;
    }

}

四、xml中的配置

<!-- 使用DES算法加密连接数据库 -->
<bean
    class="com.ssh.base.shop.utils.EncryptPropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:db.properties</value>
        </list>
    </property>
    <property name="fileEncoding" value="UTF-8" />
</bean>

完成以上配置启动项目即可。

猜你喜欢

转载自blog.csdn.net/hkhhkb/article/details/78828789