SpringBoot+数据库加密连接

Posted dream_heheda

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot+数据库加密连接相关的知识,希望对你有一定的参考价值。

1.引入依赖

<commons-io.version>2.8.0</commons-io.version>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>${commons-io.version}</version>
</dependency>

2. 写RSAUtil工具类, 包括3个方法

  • generateKeyToFile
  • decryptRSA
  • encryptRSA
import java.io.File;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class RSAUtil {

	static Logger logger = LoggerFactory.getLogger(RSAUtil.class);

	private static String algorithm = "RSA"; // 加密算法

	/**
	 * 生成密钥对并保存在本地文件中
	 *
	 * @param algorithm : 算法
	 * @param pubPath   : 公钥保存路径
	 * @param priPath   : 私钥保存路径
	 * @throws Exception
	 */
	public static void generateKeyToFile(String algorithm, String pubPath, String priPath) {

		try {
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);

			KeyPair keyPair = keyPairGenerator.generateKeyPair();

			PublicKey publicKey = keyPair.getPublic();
			PrivateKey privateKey = keyPair.getPrivate();

			byte[] publicKeyEncoded = publicKey.getEncoded();
			byte[] privateKeyEncoded = privateKey.getEncoded();

			String publicKeyString = Base64.getEncoder().encodeToString(publicKeyEncoded);
			String privateKeyString = Base64.getEncoder().encodeToString(privateKeyEncoded);
			// 保存公私钥到文件

			FileUtils.writeStringToFile(new File(pubPath), publicKeyString, Charset.forName("UTF-8"));
			FileUtils.writeStringToFile(new File(priPath), privateKeyString, Charset.forName("UTF-8"));
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}

	}

	/**
	 * @param privateKey
	 * @param encrypted  : 密文
	 * @return : 明文
	 * @throws Exception
	 */
	public static String decryptRSA(String privateKey, String encrypted) {
		try {
			if (!StringUtils.hasText(encrypted)) {
				return "";
			}
			KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
			PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
			// 生成私钥
			PrivateKey key = keyFactory.generatePrivate(spec);

			// 加密
			Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decode = Base64.getDecoder().decode(encrypted);
			byte[] bytes1 = cipher.doFinal(decode);
			return new String(bytes1);
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			return "";
		}
	}

	/**
	 * @param publicKey
	 * @param input     : 明文
	 * @return :密文
	 * @throws Exception
	 */
	public static String encryptRSA(String publicKey, String input) throws Exception {
		try {
			if (!StringUtils.hasText(input)) {
				return "";
			}
			KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
			X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));

			PublicKey key = keyFactory.generatePublic(spec);

			// 加密
			Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] bytes = cipher.doFinal(input.getBytes());
			return Base64.getEncoder().encodeToString(bytes);
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			return "";
		}
	}
}

3. 生成private key, public key,加密url, username, password

  • 调用 RSAUtil.generateKeyToFile() 方法生成private key, public key
  • 调用 RSAUtil.encryptRSA() 把配置文件中的明文url, username, password加密

4.把pulic key, private key 和 加密后的url, username, password 写入配置文件

spring.datasource.url=encrypturl
spring.datasource.username=encryptusername
spring.datasource.password=encryptpassword


# RSA public key, private key
encrypt.private-key=        
encrypt.public-key=

5.配置类

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataSourceConfig {

	@Value("${encrypt.private-key}")
	private String privateKey;

	@Value("${spring.datasource.url}")
	String jdbcUrl;

	@Value("${spring.datasource.username}")
	String username;

	@Value("${spring.datasource.password}")
	String password;

	@Bean
	public DataSource getDataSource() throws Exception {
		DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();

		dataSourceBuilder.url(RSAUtil.decryptRSA(privateKey, jdbcUrl));
		dataSourceBuilder.username(RSAUtil.decryptRSA(privateKey, username));
		dataSourceBuilder.password(RSAUtil.decryptRSA(privateKey, password));

		return dataSourceBuilder.build();
	}
}

以上是关于SpringBoot+数据库加密连接的主要内容,如果未能解决你的问题,请参考以下文章

springboot使用jasypt对配置文件加密,加密数据库连接

springboot使用jasypt对配置文件加密,加密数据库连接

SpringBoot+数据库加密连接

SpringBoot+数据库加密连接

Springboot整合Hikari数据库连接池,密码加密

配置 Druid 数据源及密码加密-SpringBoot 2.7