springboot 之 使用jasypt加密解密插件

简单使用

jasypt是一个java实现的安全框架

  • 1、该工具支持注解方式开启jasypt功能,以及注解方式引入一个或多个需要处理的配置文件。
  • 2、该工具同时支持properties与yml文件的解析处理。
  • 3、该工具支持自定义加解密类型和复写加解密方法。

引入插件

<dependency>
	<groupId>com.github.ulisesbocchio</groupId>
	<artifactId>jasypt-spring-boot-starter</artifactId>
	<version>2.1.0</version>
</dependency>

默认情况下jasypt采用的算法是PBEWithMD5AndDES,该算法对同一串明文每次加密的密文都不一样,比较适合做数据加解密。但是该算法必须配置密码 

以下是测试程序:

在配置文件中设置加解密密码

#指定加解密时使用的密码
jasypt.encryptor.password=rB8Bf1uvMvyALBoKAFfcKZuWT20208

 配置文件中设置需要加密解密的字串

#ENC表示需要解密,这里将这个配置变量注入到一个变量内,那么那个变量内容就是“123456”
#   @Value("${spring.datasource.password}")
#   private  String password;
spring.datasource.password=ENC(X+wQOPz4HKvfnSjkBi4r1w==)

 

当然我们也可以直接使用jar包生成

cd到jasypt-1.9.2.jar的当前目录,input输入要加密的字符串,password为解密时的钥匙
命令行加密:
    java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="root" password=security algorithm=PBEWithMD5AndDES
命令行解密:
    java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="i00VogiiZ1FpZR9McY7XNw==" password=security algorithm=PBEWithMD5AndDES

 

自定义加密方法

如果需要使用自定义的加减密方法,我们只需要实现StringEncryptor接口即可,具体如下:

1.实现接口

import org.jasypt.encryption.StringEncryptor;
 
public class DESEncrypt  implements StringEncryptor {
 
    //加密
    @Override
    public String encrypt(String message) {
        try {
            
            return 自己定义的方法的返回值;//如果方法中包含加密密匙那么就完全没必要在配置文件中写
        } catch (Exception e) {
            e.printStackTrace();
            return message;
        }
    }
 
    //解密
    @Override
    public String decrypt(String encryptedMessage) {
        try {
             
            return 自己定义的方法的返回值;
        } catch (Exception e) {
            e.printStackTrace();
            return encryptedMessage;
        }
    }
 
}

 2.创建bean

使用java config方式实例化该对象替换默认的StringEncryptor实例

import org.jasypt.encryption.StringEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class EncryptionConfig {
 
    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        DESEncrypt desEncrypt = new DESEncrypt();//调用我们自己实现的类即可
        return desEncrypt;
    }
}  

 

参考网址:

https://www.cnblogs.com/qingfengsuixin/p/10756604.html

https://yq.aliyun.com/articles/182720?utm_content=m_29522

https://github.com/ulisesbocchio/jasypt-spring-boot?spm=a2c4e.10696291.0.0.41fe19a4Ldsp1T

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值