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

文章目录

  • 前言
  • 一、工程整体结构
  • 二、工程搭建
    • 1.jar包引入
    • 2.数据库密码加密
    • 3.数据源配置与密码解密
    • 4.dao及sql配置
  • 三、测试
  • 总结


前言

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


一、工程整体结构

java实现对称加密—数据库密码加解密_第1张图片

二、工程搭建

1.jar包引入

<parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.0.RELEASEversion>
        <relativePath/> 
    parent>
    <dependencies>
        <dependency>
            <groupId>commons-codecgroupId>
            <artifactId>commons-codecartifactId>
            <version>1.14version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.0version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.16version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        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;
    /**
     * 加密/解密
     * 

* 算法/工作模式/填充方式 * 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();
}



<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地址

你可能感兴趣的:(java加密与解密,java,加密解密,mysql,spring,boot)