02_jayspt加密解密

项目中用jayspt来加密解密数据库信息的示例
 
引入依赖
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
 
一、自动加解密示例
# 加密盐
jasypt.encryptor.password=72ABA1A5BCA2513F92FC85544531B1605C3515EE5F7839882DB0B17B05082653A

# 数据库url
spring.datasource.url=jdbc:oracle:thin:@//10.2.77.97:1521/pdb

# 用户名
spring.datasource.username=sjb

# 加密后的密码串(ENC为固定写法)
spring.datasource.password=ENC(AQPRW0KU7BbKmfERB4xKRwGAQZcvJoj)
 
二、代码加解密示例
public class EncryptConfig {
    public static void main(String[] args) {
        System.out.println("===================加密======================");
        //加密器
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        //加密配置
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        //加密方式
        config.setAlgorithm("PBEWithMD5AndDES");
        //加密salt
        config.setPassword("1A2B3D4AHGJKAHG");
        //应用配置
        encryptor.setConfig(config);
        //要加密的密码
        String plaintext="root@1588";

        String ciphertext=encryptor.encrypt(plaintext);
        System.out.println("加密后的密码串: " + ciphertext);//QzW34Ysl9d7bD3+0GKqizf6QBu6zoxZ5

        System.out.println("===================解密======================");


        String ciphertext1="QzW34Ysl9d7bD3+0GKqizf6QBu6zoxZ5";
        //解密
        String passwd=encryptor.decrypt(ciphertext1);
        System.out.println("密码串解密后的密码 : " + passwd);//root@1588
    }
}
拓展
如果数据源是自定义数据源,且是用xml形式:
可把加密字符串放在jdbc.properties配置文件中,用代码读取然后解密,在Springboot的run方法运行之前 用System.setProperty("db","root@1588")方法放入系统属性中,然后在xml文件中用${db}读取
 
三、命令行加解密示例
默认加密方式:PBEWithMD5AndDES , 也可更改为PBEWithMD5AndTripleDES
加密命令:
java -cp jar包全路径 org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="自己需要加密的字符串" password="自己加密时的盐" algorithm="自己的加密方式"
解密命令:
java -cp jar包全路径 org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="自己需要解密的字符串" password="自己加密时的盐" algorithm="自己的加密方式"
 

 

posted @ 2021-07-18 22:56  我是多多  阅读(618)  评论(0)    收藏  举报