加密组件Jasypt学习、实战及踩坑记录

news2025/2/26 19:05:41

概述

最近入职新公司,因几乎全部项目都使用到jasypt,故而初步学习记录下本文(持续更新)。
官网及GitHub给出的简介:使用简单,性能好,特性features非常丰富;支持

另,有个开源Jasypt-spring-boot组件,GitHub,集成Jasypt,方便Spring Boot开发者使用。

实战

开发中最常见的场景就是对数据库的密码进行加密,将加密后的密码配置在Apollo等配置中心。

Jasypt

使用Jasypt需引入如下依赖:

<dependency>
    <groupId>org.jasypt</groupId>
    <artifactId>jasypt</artifactId>
    <version>1.9.3</version>
</dependency>

而数据库的密码,不要使用=root、1qaz2wsx这种极易被暴力破解的。

推荐使用在线随机密码生成器,可指定密码的位数,当然也支持指定是否包括大、小写字母、数字、特殊符号等。

借助于这个在线工具,生产随机密码FkSs3k31

直接上代码,Jasypt工具类:

@Slf4j
public class JasyptUtil {
    public static void main(String[] args) {
        String pass = "FkSs3k31";
        String salt = "johnny";
        int n = 3;
        String[] en = new String[n];
        String[] de = new String[n];
        for (int i = 0; i < n; i++) {
            en[i] = encrypt(salt, password);
            de[i] = decrypt(salt, en[i]);
            log.info("加密: " + en[i] + ",解密:" + de[i] + ",相等=" + password.equals(de[i]));
        }
    }

    public static String encrypt(String passWord, String message) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        // 加密所需的salt
        textEncryptor.setPassword(passWord);
        return textEncryptor.encrypt(message);
    }

    public static String decrypt(String passWord, String encryptor) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword(passWord);
        return textEncryptor.decrypt(encryptor);
    }
}

打印输出:

加密: G1XGWDxvGiOcDidkDTFnceNJCDr+SxPE,解密:FkSs3k31,相等=true
加密: lpLDMbDmfspxHXm0n62d1ekJin9KGwkI,解密:FkSs3k31,相等=true
加密: CvUIJ5/HU0Z201j0wDH613Z1y+445Pxu,解密:FkSs3k31,相等=true

可见每次加密得到的密码都不尽相同,但是都能够成功解密。
至于为什么要判断一下原文和解密后的是否相等,参考Java String加解密踩坑

Jasypt-spring-boot

使用Jasypt-spring-boot更是简单方便。通过前面的JasyptUtil,得到一系列数据库不同schema的加密后密码,增加前缀ENC(和后缀),放在配置中心;然后配置中心再新增一个键值对:jasypt.encryptor.password=johnny
在这里插入图片描述
添加依赖即可:

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

Spring Boot应用启动时,JasyptSpringBootAutoConfiguration会自动扫描配置类(不管是放在yml本地文件还是配置中心的),检查前缀和后缀,根据配置的加密password去解密。

应用启动打印信息:

分析

引入上述依赖后,EncryptablePropertyResolverConfiguration配置类检查前缀和后缀,

{
  "name": "jasypt.encryptor.property.prefix",
  "type": "java.lang.String",
  "description": "Specify a custom {@link String} to identify as prefix of encrypted properties. Default value is {@code \"ENC(\"}",
  "sourceType": "com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties$PropertyConfigurationProperties",
  "defaultValue": "ENC("
},
{
  "name": "jasypt.encryptor.property.suffix",
  "type": "java.lang.String",
  "description": "Specify a custom {@link String} to identify as suffix of encrypted properties. Default value is {@code \")\"}",
  "sourceType": "com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties$PropertyConfigurationProperties",
  "defaultValue": ")"
}

进阶

Jasypt

Jasypt-spring-boot

Jasypt可以为Springboot加密的信息很多,主要有:

System Property 系统变量
Envirnment Property 环境变量
Command Line argument 命令行参数
Application.properties 应用配置文件
Yaml properties 应用配置文件
other custom property sources 其它配置文件

问题

FileNotFoundException

Caused by: java.io.FileNotFoundException: class path resource [com/ulisesbocchio/jasyptspringboot/configuration/EnableEncryptablePropertiesConfiguration.class] cannot be opened because it does not exist

DecryptionException: Unable to decrypt property

应用启动失败,完整的报错信息如下:

| ERROR | org.springframework.boot.SpringApplication | reportFailure | 821 | - 
Application run failed
com.ulisesbocchio.jasyptspringboot.exception.DecryptionException: Unable to decrypt property: ENC() resolved to: ENC(). Decryption of Properties failed,  make sure encryption/decryption passwords match
at com.ulisesbocchio.jasyptspringboot.resolver.DefaultPropertyResolver.lambda$resolvePropertyValue$0(DefaultPropertyResolver.java:63)

解密失败?第一反应就是拿着这个报错的密文使用上面的工具类解密,解密成功!

参考stackoverflow,排查下来和jasypt-spring-boot-starter版本有关。

发布前版本为1.18,因应用两年多没有人维护,IDEA也一直在提示我:
在这里插入图片描述
故而想着升级pom文件里的诸多依赖,随手顺带把jasypt-spring-boot-starter的依赖升级到最新版3.0.5

参考maven repository,1.18版本后的几个主要(大)版本:2.0.02.1.03.0.0

解决方案:

  1. 版本回退到2.1.0:1.18->3.0.5->2.1.0
  2. 增加配置:
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator

验证下来,两种方案都可行,按需选择一种即可。

Failed to bind properties under ‘’ to java.lang.String

也是一个应用启动(发布)失败的问题,报错日志:

org.springframework.context.ApplicationContextException: Unable to start web server;
nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; 
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 1; 
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthIndicatorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.class]: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthIndicatorRegistry]: Factory method 'healthIndicatorRegistry' threw exception;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.mongo.MongoHealthIndicatorAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; 
nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'spring.data.mongodb-org.springframework.boot.autoconfigure.mongo.MongoProperties': Could not bind properties to 'MongoProperties' : prefix=spring.data.mongodb, ignoreInvalidFields=false, ignoreUnknownFields=true; 
nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.data.mongodb.uri' to java.lang.String

简单来说,应用启动时最底层报错为:Failed to bind properties under 'spring.data.mongodb.uri' to java.lang.String

应用使用的版本为2.1.0,

参考stackoverflow

下降到2.0.0版本解决问题。

参考

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/412975.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

leetcode刷题——字符串(双指针、滑动窗口、动态规划)

文章目录3.无重复字符的最长子串5.最长回文子串8. 字符串转换整数 (atoi)3.无重复字符的最长子串 给定一个字符串 s &#xff0c;请你找出其中不含有重复字符的 最长子串 的长度。 //双指针滑动窗口数组hash int lengthOfLongestSubstring(char * s){int hash[127] {0}; //…

生产管理系统是什么?它有哪些功能模块?

阅读本文您将了解&#xff1a;1.企业生产管理的问题&#xff1b;2.生产管理系统模块有哪些&#xff1b;3.如何利用生产管理系统模块解决问题。 一、企业生产管理会遇到哪些问题&#xff1f; 生产管理是有计划、组织、指挥、监督调节的生产活动。以最少的资源损耗&#xff0c;…

Qt Quick - Menu

Qt Quick - Menu使用总结一、概述二、上下文菜单三、弹出式菜单四、子菜单和Action五、美化一、概述 Menu其实就是Qt Quick里面的菜单控件&#xff0c;一般来说。 Menu有两种主要用例: 上下文菜单&#xff1b;例如&#xff0c;右键单击后显示的菜单弹出菜单&#xff1b;例如…

高比例可再生能源电力系统的调峰成本量化与分摊模型(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

VSCode远程调试linux

文章目录前言1. 给从机安装GCC与GDB2. 编写测试 .c文件3. 本地编译生成可执行文件4. VSCode配置4.1 拓展安装4.2 ssh连接与配置4.3 配置debug5. 开启调试前言 这个调试是基于迅为itop3568板子进行调试的&#xff0c;如果你的不是这个板子&#xff0c;其实其他的也差不多流程。…

什么是瀑布流布局?瀑布流式布局的优缺点

瀑布流又称瀑布流式布局&#xff0c;是一种多列等宽不等高的一种页面布局方式。 视觉表现为参差不齐的多栏布局。随着页面滚动条向下滚动&#xff0c;这种布局会不断加载数据并附加至当前的尾部。 是一种多列等宽不等高的一种页面布局方式&#xff0c;用于图片比较复杂&#…

Python每日一练(20230415)

目录 1. 路径总和 II &#x1f31f;&#x1f31f; 2. 两数相除 &#x1f31f;&#x1f31f; 3. 不同的二叉搜索树 II &#x1f31f;&#x1f31f; &#x1f31f; 每日一练刷题专栏 &#x1f31f; Golang每日一练 专栏 Python每日一练 专栏 C/C每日一练 专栏 Java每日…

基于小波分解+深度信念网络DBN的脑电信号分类识别

目录 背影 DBN神经网络的原理 DBN神经网络的定义 受限玻尔兹曼机(RBM) DBN的脑电信号分类识别 基本结构 主要参数 数据 MATALB代码 结果图 展望 背影 DBN是一种深度学习神经网络,拥有提取特征,非监督学习的能力,本文用DBN提取特征,用SVM分类,实现二者长处互补 DBN神…

docker在mac-m1芯片部署并启用tomcat

手把手教你使用docker在mac-m1芯片部署并启用tomcat 1&#xff0c;下载docker并安装 登陆官网下载dockr&#xff0c;选择mi芯片的docker下载 下载地址&#xff1a;https://www.docker.com/get-started 2&#xff0c;配置docker的阿里云加速器&#xff08;也可以配置其他加速…

Java_Mybatis:1. 框架概述

目录 1 什么是框架 1.1 框架的概念 1.2 框架要解决的问题 1.3 软件开发的分层重要性 1.4 分层开发下的常见框架 1.5 MyBatis 框架概述 2 JDBC 编程的分析 2.1 jdbc 程序的回顾 2.2 jdbc 问题分析 1 什么是框架 1.1 框架的概念 应用方面&#xff1a;框架&#xff08;Fra…

https://app.hackthebox.com/machines/Squashed

https://app.hackthebox.com/machines/Squashed info collecting ┌──(kwkl㉿kwkl)-[~] └─$ sudo nmap -A 10.10.11.191 -T4 …

吴 军:ChatGPT不算新技术革命,带不来什么新机会

来源: 學人Scholar 吴军&#xff0c;1967年出生&#xff0c;毕业于清华大学和约翰霍普金斯大学&#xff0c;计算机专业博士&#xff0c;前Google高级资深研究员、原腾讯副总裁、硅谷风险投资人。 4月3日晚上&#xff0c;得到直播间邀请到了计算机科学家、自然语言模型专家吴军&…

Docker安装Elasticsearch详细步骤

1 安装elasticsearch 1.1 拉取镜像 docker pull elasticsearch:7.12.11.2 创建挂载目录 mkdir -p /app/elasticsearch/confecho "http.host: 0.0.0.0" >> /app/elasticsearch/conf/elasticsearch.ymlmkdir -p /app/elasticsearch/datamkdir -p /app/elastic…

pyest+appium实现APP自动化测试,思路全总结在这里

目录 01、appium环境搭建 2、搭建pythonpytestappium环境 3、安装pycharm搭建项目编写脚本 4、执行测试 绵薄之力 01、appium环境搭建 安装nodejs http://nodejs.cn/ 为什么要安装nodejs&#xff1f; 因为appium这个工具的服务端是由nodejs语言开发的 安装jdk&#xff…

Lambda表达式的使用和省略模式

Lambda表达式的使用和省略模式一、 Lambda表达式使用1、 Lambda格式2、演示demo&#xff1a;线程启动&#xff0c;底下分别是三种实现方式3、 Lambda使用的前提4、Lambda表达式的几种类型二、省略模式1、 几种可以省略的场景2、 注意事项一、 Lambda表达式使用 1、 Lambda格式…

两种方式对el-table二次封装

1、序言 完整源码&#xff1a;el-table-example: 两种方式对el-table二次封装 最近在公司写了好多的后台管理系统&#xff0c;管理系统很大部分都是elementui下的el-table&#xff0c;el-table中有很多 <el-table-column></el-table-column>是重复的&#xff0c;像…

Redis_概述_特性_IO模型

本章要点 掌握NoSql数据库的概念和与sql数据库的区别初步了解Redis内存数据库了解Redis内存数据库的优点及其原因掌握Redis的多线程IO模型学习Redis的安装和配置 Redis简介 Redis 全称 Remote Dictionary Server 远程字典服务! 使用C语言编写,支持网络,可基于内存也可以持久化…

Scrapy爬虫框架(概念)

Scrapy 入门教程 | 菜鸟教程 (runoob.com) Scrapy是一个快速功能强大的网络爬虫框架 Scrapy的安装 通过 pip 安装 Scrapy 框架: pip install Scrapy 安装后小测&#xff1a; 执行 scrapy ‐h Scrapy不是一个函数功能库&#xff0c;而是一个爬虫框架。 Scrapy架构图(绿线是…

【ROS2指南-4】理解ROS2话题

目标&#xff1a;使用 rqt_graph 和命令行工具来反思 ROS 2 主题。 教程级别&#xff1a;初学者 时间&#xff1a; 20分钟 内容 背景 先决条件 任务 1 设置 2 rqt_graph 3 ros2主题列表 4 ros2主题回显 5 ros2 主题信息 6 ros2界面展示 7 ros2主题发布 8 ros2 主题赫…

光纤能取代网线吗?

光纤与铜缆之间的较量已持续了十多年。现如今随着云计算、5G 等新型业务的不断涌现&#xff0c;数据中心规模不断的扩大&#xff0c;其架构与布线也越来越复杂&#xff0c;而光纤的轻量化及逐渐降低的成本&#xff0c;使得主干网设备对光纤的需求也越来越旺盛&#xff0c;在大型…