java实现对称加密—数据库密码加解密
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java实现对称加密—数据库密码加解密,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6991字,纯文字阅读大概需要10分钟。
内容图文
![java实现对称加密—数据库密码加解密](/upload/InfoBanner/zyjiaocheng/865/2d48bfb0fe304894897ac4fcc4601947.jpg)
文章目录
前言
实际开发项目中,由于安全要求,数据库密码需要加密后才能存放到配置文件中。本文搭建一个简单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
)进行加密后再放到配置文件中,这里省略了。如果要加密,需要用到动态生成的根密钥,这样才避免将明文密钥存放到配置文件中。
内容总结
以上是互联网集市为您收集整理的java实现对称加密—数据库密码加解密全部内容,希望文章能够帮你解决java实现对称加密—数据库密码加解密所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。