栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 集成 Jasypt 对数据库加密以及踩坑的记录分享

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 集成 Jasypt 对数据库加密以及踩坑的记录分享

前言

密码安全是非常重要的,因此我们在代码中往往需要对密码进行加密,以此保证密码的安全

加依赖



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

加配置

# jasypt 密码加密配置
jasypt:
 encryptor:
 # 加密盐值
 password: jasypt
 # 加密算法设置 3.0.0 以后
 algorithm: PBEWithMD5AndDES
 iv-generator-classname: org.jasypt.iv.NoIvGenerator

PS:可以看到配置中特意配置了加密算法,原因是官方在 3.0.0 以后更改了加密算法,所以假如你不设置的话,使用网上的方法加密出来的密码启动就会报错,如图:

官方 issue:Failed to bind properties under ‘spring.datasource.password' to java.lang.String` #154

版本在 3.0.0 之前的 Jasypt

需要额外添加 Jasypt 的加密盐值配置到 Tomcat

-Djasypt.encryptor.password=xxxx

工具类

如果你想手动使用 Jasypt 进行加解密

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

public class JasyptUtil {

 
 public static String encyptPwd(String password,String value){
  PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
  encryptor.setConfig(cryptor(password));
  String result = encryptor.encrypt(value);
  return result;
 }

 
 public static String decyptPwd(String password,String value){
  PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
  encryptor.setConfig(cryptor(password));
  String result = encryptor.decrypt(value);
  return result;
 }

 public static SimpleStringPBEConfig cryptor(String password){
  SimpleStringPBEConfig config = new SimpleStringPBEConfig();
  config.setPassword(password);
  config.setAlgorithm("PBEWithMD5AndDES");
  config.setKeyObtentionIterations("1000");
  config.setPoolSize("1");
  config.setProviderName("SunJCE");
  config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
  config.setStringOutputType("base64");
  return config;
 }


 public static void main(String[] args) {
  // 加密
  String encPwd = encyptPwd("jasypt", "123456");
  // 解密
  String decPwd = decyptPwd("jasypt", encPwd);
  System.out.println(encPwd);
  System.out.println(decPwd);
 }
}

数据库配置解密

用官方提供的保留字 ENC,将加密的密码包裹即可

spring:
 datasource:
 url: jdbc:mysql://xx.xx.xx.xx/xxxx?useUnicode=true&characterEncoding=utf8&useSSL=false
 username: root
 password: ENC(加密后的密码)
 driver-class-name: com.mysql.jdbc.Driver

到此这篇关于SpringBoot 集成 Jasypt 对数据库加密以及踩坑的记录分享的文章就介绍到这了,更多相关SpringBoot 集成 Jasypt 对数据库加密内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/132705.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号