配置文件字段加密-jasypt
方式一(简单):采用Springboot默认加密
- pom.xml 引入jar包
<!--配置文件加密--> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.5</version> </dependency>
- 在Spring Boot应用的启动类上添加注解
@EnableEncryptableProperties
- 配置加密/解密密钥和加解密算法:在应用的配置文件中配置
#加密/解密密钥 jasypt.encryptor.password=mykey #加密算法--可不加 jasypt.encryptor.algorithm=PBEWithMD5AndDES
- 加密类,用于敏感值加密
package com.shensu.uip; import org.jasypt.encryption.StringEncryptor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; /** * * 配制文件敏感字段加密---Springboot默认加密方式--Base64加密 * */ @SpringBootTest public class JasyptTest { @Autowired private StringEncryptor stringEncryptor; @Test public void encryptPwd() { String dataPassWord = "abcd14321"; System.out.println(dataPassWord+"~"+stringEncryptor.encrypt(dataPassWord)); } }
- 加密后在配置文件这样用
spring.datasource.password=ENC(d8ac846f8ac450004f077b57c1616666)
方式二(重写用自己的加密方式):采用sm4加密
- 方式一的1、2、5不变
- 重写StringEncryptor类,如下
package com.shensu.uip.aspect; import com.shensu.uip.utils.SM4Util; import org.jasypt.encryption.StringEncryptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * 配置文件敏感字段加密--sm4加密 * @author Joy * @date 2024年12月12日 */ @Component("customStringEncryptor") class JasyptStringEncryptor implements StringEncryptor { /** * @Fields LOGGER : 日志 */ private static final Logger LOGGER = LoggerFactory.getLogger(JasyptStringEncryptor.class); /** * 加密 * @param message * @return */ @Override public String encrypt(final String message) { final String exMsg = SM4Util.encryptCloud(message); throw new UnsupportedOperationException(exMsg); } /** * 解密 * @param encryptedMessage * @return */ @Override public String decrypt(final String encryptedMessage) { String decryptedMessage; try { decryptedMessage = SM4Util.decryptCloud(encryptedMessage); //System.out.println("解密:" + decryptedMessage); } catch (Exception e) { LOGGER.error("decrypt failed, key: '{}'.", encryptedMessage, e); throw new RuntimeException(e); } return decryptedMessage; } }
- 配置文件修改
#去掉key #jasypt.encryptor.password=mykey #配自定义加解密方式 jasypt.encryptor.bean = customStringEncryptor

浙公网安备 33010602011771号