• Springboot引入jasypt实现加解密


    一、前言
    有时在实际应用中,我们可能需要使用到一些秘钥,针对某些资源文件中的内容通常情况下是明文显示,安全性就比较低一些,比如redis登陆密码以及第三方的密钥等等一览无余,这时就可以使用jasypt来实现加解密。

    二、如何实现?
    1.引入Maven jar包

    <dependency>
         <groupId>com.github.ulisesbocchio</groupId>
         <artifactId>jasypt-spring-boot-starter</artifactId>
         <version>3.0.3</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.application.yml文件中增加jasypt的秘钥(该秘钥自定义的):

    jasypt:
     encryptor:
     #加密秘钥
     password: Eb12kitulv73I2p21XI507
    
    • 1
    • 2
    • 3
    • 4

    3.接着写个测试类。

    @RestController
    public class IndexController {
    
     @Autowired
     private StringEncryptor encryptor;
    
     /**
     * 测试jasypt加密解密
     */
     @GetMapping("/test")
     public void testJasypt() {
     	String password = "12345678";
     	String encryptPwd = encryptor.encrypt(password);
     	System.out.println("加密::" + encryptPwd);
     	System.out.println("解密:" + encryptor.decrypt(encryptPwd));
     }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    jasypt由于其使用的是PBEWithMD5AndDES加密方式,所以每次加密出来的结果都不一样,但是解密都是一样的,所以很适合对数据进行加密。

    4.将加解密秘钥放在配置文件中是不安全的,有如下几种解决办法:
    1)、在启动类上赋值秘钥:

    @SpringBootApplication
    public class ProviderApplication {
    
     public static void main(String[] args) {
     /** 配置加解密秘钥,与配置文件的密文分开放 */
     System.setProperty("jasypt.encryptor.password", "suntree@qwe!!");
    
     SpringApplication.run(ProviderApplication.class, args);
     }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    1. 自定义StringEncryptor
    /**
     * 配置StringEncryptor
     */
     @Bean("jasyptStringEncryptor")
     public StringEncryptor stringEncryptor() {
     	PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
     	SimpleStringPBEConfig config = new SimpleStringPBEConfig();
     	config.setPassword("suntree@qwe!!");
     	config.setAlgorithm("PBEWithMD5AndDES");
     	config.setKeyObtentionIterations("1000");
     	config.setPoolSize("1");
     	config.setProviderName("SunRTE");
     	config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
     	config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");
     	config.setStringOutputType("base64");
     	encryptor.setConfig(config);
     return encryptor;
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    线阵相机之帧超时
    java 串口通讯
    基于cortex-M3,M4下硬件层、驱动层的解耦软件框架设计
    [附源码]java毕业设计基于的疫苗预约系统
    【Linux】 uptime命令使用
    聊聊RabbitMQ
    learn C++ NO.4 ——类和对象(2)
    淘宝商家私信脚本,自动批量阿里旺旺版,按键精灵源码分享
    全志芯片Tina Linux 修改 UART 引脚、UART端口 (2)
    MFC发送http https以及json解析
  • 原文地址:https://blog.csdn.net/qq_42077317/article/details/133774710