Spring中管理数据源,加密和解密账号密码的方法

开始有一篇关于SSH框架上加密、解密读取properties上的文件,现使用另一种方式来实现


首先:工具类DESUtils

import java.security.Key;
import java.security.SecureRandom;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class DESUtils {
 
    private static Key key;
    private static String KEY_STR = "myKey";// 密钥
    private static String CHARSETNAME = "UTF-8";// 编码
    private static String ALGORITHM = "DES";// 加密类型
 
    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            generator.init(new SecureRandom(KEY_STR.getBytes()));
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 对str进行DES加密
     * 
     * @param str
     * @return
     */
    public static String getEncryptString(String str) {
        BASE64Encoder base64encoder = new BASE64Encoder();
        try {
            byte[] bytes = str.getBytes(CHARSETNAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return base64encoder.encode(doFinal);
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 对str进行DES解密
     * 
     * @param str
     * @return
     */
    public static String getDecryptString(String str) {
        BASE64Decoder base64decoder = new BASE64Decoder();
        try {
            byte[] bytes = base64decoder.decodeBuffer(str);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSETNAME);
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
 
}


工具类:EncryPtPropertyPlaceholderConfigurer

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
 
/**
 * 继承PropertyPlaceholderConfigurer定义支持密文版属性的属性配置器
 * 
 * @author moziqi
 * 
 */
public class EncryptPropertyPlaceholderConfigurer extends
        PropertyPlaceholderConfigurer {
    private String[] encryptPropNames = { "userName", "password" };
 
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        if (isEncryptProp(propertyName)) {
            String decryptValue = DESUtils.getDecryptString(propertyValue);
            System.out.println(propertyName + "解密内容:" + decryptValue);
            return decryptValue;
        } else {
            return propertyValue;
        }
    }
 
    /**
     * 判断是否是加密的属性
     * 
     * @param propertyName
     * @return
     */
    private boolean isEncryptProp(String propertyName) {
        for (String encryptpropertyName : encryptPropNames) {
            if (encryptpropertyName.equals(propertyName))
                return true;
        }
        return false;
    }
}

测试的properties文件

dbName=sampledb
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/${dbName}
#userName=root
#password=123456
userName=WnplV/ietfQ=
password=QAHlVoUc49w=


spring中的数据源bean配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!--1.使用传统的PropertyPlaceholderConfigurer引用属性文件 -->
    <!-- bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:fileEncoding="utf-8"> <property name="locations"> <list> <value>classpath:com/baobaotao/placeholder/jdbc.properties</value> 
        </list> </property> </bean -->
 
    <!--2.使用context命名空间的配置引用属性文件 -->
    <!--context:property-placeholder location="classpath:com/baobaotao/placeholder/jdbc.properties"
        file-encoding="utf8"/> <bean id="utf8" class="java.lang.String"> <constructor-arg 
        value="utf-8"></constructor-arg> </bean -->
 
    <!--3.使用加密版的属性文件 -->
    <bean class="com.spring.util.EncryptPropertyPlaceholderConfigurer"
        p:location="classpath:jdbc.properties" p:fileEncoding="utf-8" />
 
    <context:component-scan base-package="com.spring.*" />
 
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}"
        p:username="${userName}" p:password="${password}" />
</beans>




  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 项目,我们可以使用 Spring Security 提供的 BCryptPasswordEncoder 类来实现密码加密解密。 1. 导入 Spring Security 依赖 在 pom.xml 文件添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 加密密码 在注册或修改密码时,需要将明文密码加密后再存储到数据库。可以通过以下代码实现密码加密: ```java import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; String password = "123456"; BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(password); ``` 其,`password` 是需要加密的明文密码,`passwordEncoder` 是一个 BCryptPasswordEncoder 对象,`hashedPassword` 是加密后的密码。 3. 验证密码 在用户登录时,需要将用户输入的密码与数据库加密密码进行比较。可以通过以下代码实现密码验证: ```java import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; String password = "123456"; String hashedPassword = "$2a$10$L0H8jxHr6xQe3xHbBsQnBuX8Kq4oL0X0qZt6N1PfX6X4Ck4fFK7sW"; BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); boolean result = passwordEncoder.matches(password, hashedPassword); ``` 其,`password` 是用户输入的密码,`hashedPassword` 是从数据库读取出来的加密密码,`passwordEncoder` 是一个 BCryptPasswordEncoder 对象,`result` 表示密码验证的结果,如果密码匹配成功则返回 true,否则返回 false。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值