jasypt 加密

jasypt 官网:
https://github.com/ulisesbocchio/jasypt-spring-boot

参考:
https://zhiku8.com/springboot-jasypt.html

一:pom



    com.github.ulisesbocchio
    jasypt-spring-boot-starter
    2.0.0

二:yml配置文件中引入passwodk,也就是盐

# 配置文件加密key
jasypt:
  encryptor:
    password: panther

三:创建工具包

package com.xxx.xxx.xxx;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * @Created with Intellij IDEA
 * @Author : 
 * @Date : 2018/5/18 - 10:37
 * @Copyright (C), 2018-2018
 * @Descripition : Jasypt安全框架加密类工具包
 */
public class JasyptUtils {

    /**
     * Jasypt生成加密结果
     *
     * @param password 配置文件中设定的加密密码 jasypt.encryptor.password
     * @param value    待加密值
     * @return
     */
    public static String encryptPwd(String password, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(password));
        String result = encryptOr.encrypt(value);
        return result;
    }

    /**
     * 解密
     *
     * @param password 配置文件中设定的加密密码 jasypt.encryptor.password
     * @param value    待解密密文
     * @return
     */
    public static String decyptPwd(String password, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(password));
        String result = encryptOr.decrypt(value);
        return result;
    }

    /**
     * @param password salt
     * @return
     */
    public static SimpleStringPBEConfig cryptOr(String password) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName(null);
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        return config;
    }

    public static void main(String[] args) {
        // 加密
        System.out.println(encryptPwd("EbfYkitulv73I2p0mXI50JMXoaxZTKJ7", "root@1234"));
        // 解密
//        mysql@1234
//        System.out.println(decyptPwd("EbfYkitulv73I2p0mXI50JMXoaxZTKJ7", "bgWQ4OfVCUJ1ExsqNhGV+KKBgpx8alv+"));

//        root@1234
//        System.out.println(decyptPwd("EbfYkitulv73I2p0mXI50JMXoaxZTKJ7", "tdHzge8YvviOJaiV/+P6uQ9wgB44D1aH"));
    }

}

四:使用方法
运行main方法,填入配置的盐,然后填入需要加密的value,直接运行即可。

类似配置文件中的数据库连接

# 开发环境
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/panther_dev?useUnicode=true&characterEncoding=UTF-8
    # Jasypt加密 可到common包中找到JasyptUtil加解密工具类生成加密结果 格式为ENC(加密结果)
    username: ENC(S2G86yhb0OMJMeNXUaGwYw==)
    password: ENC(GfP4qfnrJeqMvzN1nOemIQ==)

你可能感兴趣的:(jasypt 加密)