springboot配置文件中敏感数据(账号密码)加密

文章介绍了在项目部署到实际环境中遇到安全检查要求整改明文配置的数据库和中间件账号密码的问题。作者推荐使用Jasypt工具进行加密,并详细阐述了引入Jasypt依赖、创建加密工具类、配置文件设置以及如何替换账号密码的过程。还提及了对其他敏感数据加密的预研计划。
摘要由CSDN通过智能技术生成

背景:

原本项目中数据库和中间件账号密码都是直接用明文配置的,毕竟这样最方便开发,平时也没人在乎这个。但是部署到实际项目中,甲方进行安全检查第一个就查到这个,要求我们整改,那只能整了。

网上找了一些资料,好像大都用Jasypt加密工具操作,Jasypt官网看其他博客看了下,发现使用起来比较方便,直接简单记录下,

扩展:直接预研敏感数据加密技术,不只是对配置文件加密,对其他接口经过后台的敏感数据也进行了解,包括数据加密、加密后的技术怎么进行模糊查询等等,会在后续博客中进行编写。当然这都是后话,下面直接操作Jasypt进行配置文件账号密码加密。

实践Jasypt

1、引入依赖

    <!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
    <dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot-starter</artifactId>
        <version>3.0.5</version>
    </dependency>

如果项目中启动类没有 @SpringBootApplication或@EnableAutoConfiguration注解,那么需要引入jasypt-spring-boot依赖且需要创建配置类并启用 @Configuration和@EnableEncryptableProperties,进行声明。

2、账号密码转成加密值

创建一个工具类把我们的账号密码进行加密

import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Jasypt加密工具类
* @author ppp
* @date 2023/1/5
*/
public class JasyptUtil {
    private static final Logger logger = LoggerFactory.getLogger(JasyptUtil.class);
    /**
     * 加密使用密钥,需要在和配置文件中的jasypt.encryptor.password保持一致	
     */
    private static final String PRIVATE_KEY = "demo";
    /**
     * BasicTextEncryptor对象初始化使用的算法就是"PBEWithMD5AndDES"
     * 点击进源码构造方法中就可以看到下面的设置
     * this.encryptor.setAlgorithm("PBEWithMD5AndDES");
     */
    private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();

    static {
        basicTextEncryptor.setPassword(PRIVATE_KEY);
    }
    /**
     * 明文加密
     *
     * @param plaintext 明文
     * @return String
     */
    public static String encrypt(String plaintext) {
        logger.info("明文字符串为:{}", plaintext);
        String ciphertext = basicTextEncryptor.encrypt(plaintext);
        logger.info("密文字符串为:{}", ciphertext);
        return ciphertext;
    }

    /**
     * 解密
     *
     * @param ciphertext 密文
     * @return String
     */
    public static String decrypt(String ciphertext) {
        logger.info("密文字符串为:{}", ciphertext);
        ciphertext = "ENC(" + ciphertext + ")";
        if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
            String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
            logger.info("明文字符串为:{}", plaintext);
            return plaintext;
        }
        logger.error("解密失败!");
        return "";
    }

    public static void main(String[] args) {
        String encrypt = encrypt("123456");
        String test = decrypt(encrypt);
    }
}

3、配置文件添加配置

application.yml中添加配置

jasypt:
  encryptor:
    # 指定加密密钥,生产环境请放到启动参数里面 -Djasypt.encryptor.password=加密密钥
    password: demo
    # 指定解密算法,需要和加密时使用的算法一致
    algorithm: PBEWithMD5AndDES
    # 指定initialization vector类型
    iv-generator-classname: org.jasypt.iv.NoIvGenerator

4、替换账号密码

把application.yml中需要加密的账号密码都换成 ENC(密文) 格式即可,启用项目后他会检测配置文件中ENC样式的数据把里面的密文解密出来给框架使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis-plus提供了加密拦截器`MybatisPlusInterceptor`,可以在查询和修改时对敏感数据进行加密和解密操作。以下是在Spring Boot配置Mybatis-plus加密拦截器的步骤: 1. 首先,需要在pom.xml文件添加mybatis-plus-boot-starter依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> ``` 2. 创建一个`MetaObjectHandler`实现类,该类可以在插入和更新时自动填充公共字段,例如创建时间、修改时间等。在该类,需要实现`insertFill`和`updateFill`方法,并在需要自动填充的字段上添加`@TableField(fill = FieldFill.INSERT)`和`@TableField(fill = FieldFill.UPDATE)`注解。 ```java @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); } @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); } } ``` 3. 创建一个加密拦截器`EncryptInterceptor`,该拦截器可以在查询和修改时对敏感数据进行加密和解密操作。在该拦截器,需要实现`intercept`方法,并在需要加密的字段上添加`@TableField(fill = FieldFill.INSERT_UPDATE)`注解。 ```java @Component public class EncryptInterceptor implements Interceptor { private static final String AES_KEY = "1234567890123456"; private static final String CHARSET = "UTF-8"; @Override public Object intercept(Invocation invocation) throws Throwable { Object parameter = invocation.getArgs()[1]; if (parameter instanceof MappedStatement && ((MappedStatement) parameter).getId().contains("update")) { MetaObject metaObject = SystemMetaObject.forObject(parameter); String[] propertyNames = metaObject.getSetterNames(); for (String propertyName : propertyNames) { if (metaObject.hasSetter(propertyName) && metaObject.hasGetter(propertyName)) { TableField tableField = metaObject.getOriginalObject().getClass().getDeclaredField(propertyName) .getAnnotation(TableField.class); if (tableField != null && tableField.fill() == FieldFill.UPDATE) { Object value = metaObject.getValue(propertyName); if (value != null && value instanceof String) { metaObject.setValue(propertyName, encrypt((String) value)); } } } } } return invocation.proceed(); } private String encrypt(String content) throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(AES_KEY.getBytes()); keygen.init(128, random); SecretKey secretKey = keygen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); byte[] byteContent = content.getBytes(CHARSET); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] byteRresult = cipher.doFinal(byteContent); return Base64.encodeBase64String(byteRresult); } } ``` 4. 在配置文件配置Mybatis-plus的加密拦截器和自动填充功能: ```yaml mybatis-plus: global-config: meta-object-handler: com.example.demo.handler.MyMetaObjectHandler configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl interceptors: - com.example.demo.interceptor.EncryptInterceptor ``` 5. 在需要加密的字段上添加`@TableField(fill = FieldFill.INSERT_UPDATE)`注解,例如: ```java @TableField(fill = FieldFill.INSERT_UPDATE) private String password; ``` 通过以上步骤,就可以在Spring Boot配置Mybatis-plus加密拦截器了。注意,在实际应用,需要对加密算法、加密密钥等进行更加严格的保护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值