java实现对称加密—数据库密码加解密


前言

实际开发项目中,由于安全要求,数据库密码需要加密后才能存放到配置文件中。本文搭建一个简单WEB工程,使用AES算法生成密钥,使用AES/CBC/PKCS5Padding算法对数据密码加密与解密,并完成从数据库中获取数据。


一、工程整体结构

工程结构

二、工程搭建

1.jar包引入

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.14</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

2.数据库密码加密

引入加密工具类CipherUtils

public class CipherUtils {
    // 使用AES算法
    private static final String KEY_ALGORITHM = "AES";
    // 密钥长度
    private static int KEY_SIZE = 128;

    // iv长度
    private static int IV_SIZE = 16;
    /**
     * 加密/解密
     * <p>
     * 算法/工作模式/填充方式
     * ECB mode cannot use IV
     */
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 使用AES算法生成密钥
     *
     * @return 16进制的密钥
     * @throws NoSuchAlgorithmException 指定算法不存在
     */
    public static String initAESKeyHex() throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(KEY_SIZE);
        SecretKey secretKey = kg.generateKey();
        byte[] encoded = secretKey.getEncoded();
        // 装换成16进制
        return Hex.encodeHexString(encoded);
    }

    /**
     * 转换成密钥材料
     *
     * @param key 明文密钥
     * @return 密钥材料
     * @throws Exception Exception
     */
    private static Key toKey(byte[] key) throws Exception {
        return new SecretKeySpec(key, KEY_ALGORITHM);
    }

    /**
     * 加密
     *
     * @param data 明文
     * @param key  密钥
     * @return 密文
     * @throws Exception Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        // 将16进制的key转换回去
        byte[] keyByte = Hex.decodeHex(key);
        // 获取随机的安全IV值
        byte[] salt = secureRandom(IV_SIZE);
        String cipherText = encrypt(data.getBytes(StandardCharsets.UTF_8), salt, keyByte);
        // 将iv与加密后的数据拼接返回
        return Hex.encodeHexString(salt) + ":" + cipherText;
    }

    /**
     * 解密
     *
     * @param data 密文base64字符串
     * @param key  密钥
     * @return 明文
     * @throws Exception Exception
     */
    public static String decrypt(String data, String key) throws Exception {
        if (!data.contains(":")) {
            throw  new IllegalArgumentException();
        }
        // 先获取iv值
        byte[] salt = Hex.decodeHex(data.substring(0, data.indexOf(":")));
        // 获取数据部分
        byte[] cipherText = Hex.decodeHex(data.substring(data.indexOf(":") + 1));
        return decrypt(cipherText, salt, Hex.decodeHex(key));
    }

    /**
     * 加密
     *
     * @param data 明文
     * @param salt iv值
     * @param key  密钥
     * @return 加密后16进制字符串
     * @throws Exception Exception
     */
    private static String encrypt(byte[] data, byte[] salt, byte[] key) throws Exception {
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, k, new IvParameterSpec(salt));
        return Hex.encodeHexString(cipher.doFinal(data));
    }

    /**
     * 加密
     *
     * @param data 密文
     * @param salt iv值
     * @param key  密钥
     * @return
     * @throws Exception Exception
     */
    private static String decrypt(byte[] data, byte[] salt, byte[] key) throws Exception {
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(salt));
        return new String(cipher.doFinal(data), StandardCharsets.UTF_8);
    }

    private static byte[] secureRandom(int len) throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstanceStrong();
        byte[] bytes = new byte[len];
        random.nextBytes(bytes);
        return bytes;
    }
}

运行加密自己的数据库密码,放到工程的配置文件中

public class EncryptDataBasePassword {
    public static void main(String[] args) throws Exception {
        // 先获取AES的密钥
        String key = CipherUtils.initAESKeyHex();
        System.out.println("key: " + key);
        // 用上一步的密钥对数据库密码的明文进行AES128加密
        String encrypt = CipherUtils.encrypt("123456", key);
        System.out.println("encryptText: " + encrypt);
        // 将以上产生的encryptText放到配置文件中
    }
}

3.数据源配置与密码解密

application.properties文件配置

server.port=56000
spring.application.name=myServer
#DB Configuration:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.158.132:3306/order_db?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
# 这里用的是加密后的密文
spring.datasource.password=f7ccdd84afbe7dabc9b82c109d50409b:804a369c9b86f8c7295e8dd095986fac
mybatis.mapper-locations=classpath:mapping/*.xml

配置文件中配置了密文(密文运行工具类获得),需要在自定义配置类DataSourceConfiguration中进行解密

@Configuration
@PropertySource("classpath:workKey.properties")
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceConfiguration {
    @Resource
    DataSourceProperties dataSourceProperties;

    @Value("${db.workKey}")
    private String dbWorkKey;

    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setUsername(dataSourceProperties.getUsername());
        try {
          // 这里进行解密
            String password = CipherUtils.decrypt(dataSourceProperties.getPassword(), dbWorkKey);
            druidDataSource.setPassword(password);
            return druidDataSource;
        } catch (Exception e) {
            System.out.println("解密失败");
            throw new RuntimeException();
        }
    }
}

其中,密钥配置在另一个配置workKey.properties

db.workKey=c27d21b79f499a9c9bebaf8d631ad78f 

4.dao及sql配置

@Mapper
public interface OrderMapper {
    List<Order> findAll();
}
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.mapper.OrderMapper">
    <select id="findAll" resultType="com.bean.Order">
       select order_id as orderId,
               price as price,
               user_id as userId,
               status
        from t_order
        order by order_id limit 0,10;
    </select>
</mapper>

三、测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class DataBaseCipherTest {
    @Autowired
    private OrderMapper mapper;
    
    @Test
    public void selectWithNoEncrypt() {
        List<Order> results = mapper.findAll();
        System.out.println(results.size());
    }
}

总结

实际项目中,原则上也要对aes的密钥(上述配置项db.workKey)进行加密后再放到配置文件中,这里省略了。如果要加密,需要用到动态生成的根密钥,这样才避免将明文密钥存放到配置文件中。
完整代码:github地址

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值