文件管理 · 2022年9月15日

spring配置文件加密|springboot上传文件到服务器aes加密

1. 如何对数据库进行加密和解密

数据库账号密码加密详解及实例数据库中经常有对数据库账号密码的加密,但是碰到一个问题,在使用UserService对密码进行加密的时候,spring security 也是需要进行同步配置的,因为spring security 中验证的加密方式是单独配置的。如下:<authentication-manager> <authentication-provider user-service-ref="userDetailService"> <password-encoder ref="passwordEncoder" /> </authentication-provider></authentication-manager><beans:bean class="com.sapphire.security.MyPasswordEncoder" id="passwordEncoder"> <beans:constructor-arg value="md5"></beans:constructor-arg></beans:bean>如上述配置文件所示,passwordEncoder才是在spring security对账号加密校验的地方。spring security在拦截之后,会首先对用户进行查找,通过自己定义的userDetailService来找到对应的用户,然后由框架进行密码的匹配验证。从userDetailService得到user以后,就会进入到DaoAuthenticationProvider中,这是框架中定义的 ,然后跳入其中的authenticate方法中。 该方法会进行两个检查,分别是* preAuthenticationChecks : 主要进行的是对用户是否过期等信息的校验,调用的方法在userDetail中有定义的。* : 这个就是用户名密码验证的过程了。而PasswordEncoder是我们xml中注入的bean,所以了,我们调用的则是我们自己完成的passwordEncoderpublic class MyPasswordEncoder extends MessageDigestPasswordEncoder { public MyPasswordEncoder(String algorithm) { super(algorithm); } @Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) { return encPass.equals(DigestUtils.md5DigestAsHex(rawPass.getBytes())); }}这是我对其实现的一个简单版本,调用的就是spring自带的加密算法,很简单了,当然也可以使用复杂的加密方法,这个就靠自己了感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

2. spring boot调用加密狗

java开发加密狗的应用程序,应用于web项目。springboot项目加密解决方案:配置pomxml用maven直接构建加密后的jar包。使用maven构建jar包;如果springboot项目使用到了JPA并且是用hibernate实现的,那么启动加密后的jar是会报错的,创建服务命令:管理员进入cmd输入 WinSWNET,exe install 即可创建服务;启动服务即可。”加密锁”(也称加密狗)最早由彩虹天地开发,现已成为软件加密行业的代名词。加密锁是为软件开发商提供的一种智能型的具有软件保护功能的工具,它包含一个安装在计算机并行口或 USB 口上的硬件,及一套适用于各种语言的接口软件和工具软件。加密锁基于硬件保护技术,其目的是通过对软件与数据的保护防止知识产权被非法使用。

3. SpringBoot配置属性-Security

security.basic.authorize-mode 要使用权限控制模式. security.basic.enabled 是否开启基本的鉴权,默认为true security.basic.path 需要鉴权的path,多个的话以逗号分隔,默认为[/**] security.basic.realm HTTP basic realm 的名字,默认为Spring security.enable-csrf 是否开启cross-site request forgery校验,默认为false. security.filter-order Security filter chain的order,默认为0 security.headers.cache 是否开启http头部的cache控制,默认为false. security.headers.content-type 是否开启X-Content-Type-Options头部,默认为false. security.headers.frame 是否开启X-Frame-Options头部,默认为false. security.headers.hsts 指定HTTP Strict Transport Security (HSTS)模式(none, domain, all). security.headers.xss 是否开启cross-site scripting (XSS) 保护,默认为false. security.ignored 指定不鉴权的路径,多个的话以逗号分隔. security.oauth2.client.access-token-uri 指定获取access token的URI. security.oauth2.client.access-token-validity-seconds 指定access token失效时长. security.oauth2.client.additional-information.[key] 设定要添加的额外信息. security.oauth2.client.authentication-scheme 指定传输不记名令牌(bearer token)的方式(form, header, none,query),默认为header security.oauth2.client.authorities 指定授予客户端的权限. security.oauth2.client.authorized-grant-types 指定客户端允许的grant types. security.oauth2.client.auto-approve-scopes 对客户端自动授权的scope. security.oauth2.client.client-authentication-scheme 传输authentication credentials的方式(form, header, none, query),默认为header方式 security.oauth2.client.client-id 指定OAuth2 client ID. security.oauth2.client.client-secret 指定OAuth2 client secret. 默认是一个随机的secret. security.oauth2.client.grant-type 指定获取资源的access token的授权类型. security.oauth2.client.id 指定应用的client ID. security.oauth2.client.pre-established-redirect-uri 服务端pre-established的跳转URI. security.oauth2.client.refresh-token-validity-seconds 指定refresh token的有效期. security.oauth2.client.registered-redirect-uri 指定客户端跳转URI,多个以逗号分隔. security.oauth2.client.resource-ids 指定客户端相关的资源id,多个以逗号分隔. security.oauth2.client.scope client的scope security.oauth2.client.token-name 指定token的名称 security.oauth2.client.use-current-uri 是否优先使用请求中URI,再使用pre-established的跳转URI. 默认为true security.oauth2.client.user-authorization-uri 用户跳转去获取access token的URI. security.oauth2.resource.id 指定resource的唯一标识. security.oauth2.resource.jwt.key-uri JWT token的URI. 当key为公钥时,或者value不指定时指定. security.oauth2.resource.jwt.key-value JWT token验证的value. 可以是对称加密或者PEMencoded RSA公钥. 可以使用URI作为value. security.oauth2.resource.prefer-token-info 是否使用token info,默认为true security.oauth2.resource.service-id 指定service ID,默认为resource. security.oauth2.resource.token-info-uri token解码的URI. security.oauth2.resource.token-type 指定当使用userInfoUri时,发送的token类型. security.oauth2.resource.user-info-uri 指定user info的URI security.oauth2.sso.filter-order 如果没有显示提供WebSecurityConfigurerAdapter时指定的Filter order. security.oauth2.sso.login-path 跳转到SSO的登录路径默认为/login. security.require-ssl 是否对所有请求开启SSL,默认为false. security.sessions 指定Session的创建策略(always, never, if_required, stateless). security.user.name 指定默认的用户名,默认为user. security.user.password 默认的用户密码. security.user.role 默认用户的授权角色.

4. springboot上传文件到服务器aes加密

业务需求:数据库中的用户名密码明文存储在配置文件中,不是十分安全。所以将数据库中的用户名密码使用AES对称加密放入配置文件中,达到加密效果。同时也不想使用tomcat等中间件等太繁重,就使用了spring boot 轻量级框架。个人比较菜,轻喷。 关于如何搭建spring boot项目其他的人说的很详细 参考初识Spring Boot框架

入口类代码

@Controller@SpringBootApplication@EnableAutoConfiguration{publicstaticvoidmain(String[]args){SpringApplication.run(Aesdemo1Application.class,args);}}

运行时只要运行main方法 或者打包后java -jar 即可(写成.bat文件 点击运行方便简单)

@ControllerpublicclassGetKeyController{@GetMapping("/getkey")publicStringgreetingForm(Modelmodel){model.addAttribute("passwordBean",newPasswordBean());return"index";}@PostMapping("/getkey")publicStringgreetingSubmit(@){Strings1=AESUtil.encrypt(passwordBean.getPassword(),passwordBean.getVar1());passwordBean.setVar2(s1);return"result";}}

启动后有这里还有一个控制器类 浏览器地址输入 http://localhost:8080/getkey 即可跳转到greetingForm 方法,赋入PasswordBean属性后 跳转到index.html PasswordBean 是自己定义的bean类 里面有password var1 var2 3个属性

index.html代码

<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metacharset="UTF-8"/><title>Title</title></head><body><formaction="#"th:action="@{/getkey}"th:object="${passwordBean}"method="post"><p>密码:<inputtype="text"th:field="*{password}"/></p><p>加密字符:<inputtype="text"th:field="*{var1}"/></p><p><inputtype="submit"value="Submit"/><inputtype="reset"value="Reset"/></p></form></body></html>

注意使用了thymeleaf框架 所以必须引入

输入要加密的和盐即可获得通过post方法到result即可获得加密后字符串

<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metacharset="UTF-8"/><title>Title</title></head><body><h1>Result</h1><pth:text="'密码:'+${passwordBean.password}"/><pth:text="'加密字符:'+${passwordBean.var1}"/><pth:text="'加密后字符:'+${passwordBean.var2}"/><ahref="/getkey">Submitanothermessage</a></body></html>

5. SpringBoot 配置文件详解(告别XML)

快速学会和掌握 SpringBoot 的 核心配置文件的使用。

SpringBoot 提供了丰富的 外部配置 ,常见的有:

其中核心配置文件我们并不陌生,主要以Key-Value的形式进行配置,其中属性Key主要分为两种:

在 application.properties 添加配置如下:

① 添加数据源信息

在 application.propertis 添加配置如下:

① 添加认证信息,其中 socks.indentity.* 是自定义的属性前缀。

② 添加随机值,其中spring.test.* 是自定义的属性前缀。

使用方法: @ConfigurationProperties(prefix = “spring.datasource”)

使用说明:提供 Setter方法 和 标记组件 Component

如何验证是否成功读取配置?答:这里可以简单做个验证,注入 MyDataSource ,使用 Debug 模式可以看到如下信息:

使用方法: @Value(“spring.datasource.*”)

使用说明:提供 Setter方法 和 标记组件 Component

注意事项:@Value不支持注入静态变量,可间接通过Setter注入来实现。

关于两者的简单功能对比:

显然,前者支持松绑定的特性更强大,所以在实际开发中建议使用@ConfigurationProperties来读取自定义属性。

SpringBoot 默认会加载这些路径加载核心配置文件,按优先级从高到低进行排列:具体规则详见 ConfigFileApplicationListener

如果存在多个配置文件,则严格按照优先级进行覆盖,最高者胜出:

举个简单的例子,例如再上述位置都有一个application.properties ,并且每个文件都写入了server.port=xx (xx分别是9001,9002,9003,9004),在启动成功之后,最终应用的端口为:9004。图例:

如果想修改默认的加载路径 或者 调改默认的配置文件名,我们可以借助命令行参数进行指定,例如:

YAML是JSON的一个超集,是一种可轻松定义层次结构的数据格式。

答: 因为配置文件这东西,结构化越早接触越规范越好。这里推荐阅读阮一峰老师写的 YAML语言教程 ,写的很简单明了。

引入依赖: 在POM文件引入 snakeyaml 的依赖。

使用说明: 直接在类路径添加 application.yml 即可。

例如下面这两段配置是完全等价的:

① 在 application.yml 配置数据源:

② 在 application.properties 配置数据源:

在项目的实际开发中,我们往往需要根据不同的环境来加载不同的配置文件。例如生产环境,测试环境和开发环境等。此时,我们可以借助 Profiles 来指定加载哪些配置文件。例如:

温馨提示:如果spring.profiles.active指定了多个配置文件,则按顺序加载,其中最后的优先级最高,也就是最后的会覆盖前者。

使用方法: 使用Maven插件打包好项目,然后在当前路径,执行DOS命令: java -jar demo.jar –server.port=8081 ,在控制台可看到应用端口变成了8081。

实现原理: 默认情况下,SpringBoot会将这些命令行参数转化成一个 Property ,并将其添加到 Environment 上下文。

温馨提示: 由于命令行参数优先级非常之高,基本高于所有常见的外部配置,所以使用的时候要谨慎。详见 PropertySource 执行顺序 。

关闭方法: 如果想禁用命令行属性,可以设置如下操作:springApplication.setAddCommandLineProperties(false)

6. spring配置文件中的数据库用户名和密码怎么加密

一般spring容器启动时,通过PropertyPlaceholderConfigurer类读取jdbc.properties文件里的数据库配置信息。通过这个原理,我们把加密后的数据库配置信息放到jdbc.properties文件里,然后自定义一个继承PropertyPlaceholderConfigurer的类重写processProperties方法,实现解密,把解密后的信息又放回去。

7. 怎么能让spring框架加载加密后的.class文件

加密:使用AES加密,将文件的字节码读取,对字节码进行加密后替换源文件Java代码 /** * * 字节加密 */ public static byte[] encrypt(byte[] data, String key) throws Exception { Key k = toKey(Base64.decode(key)); byte[] raw = k.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); return cipher.doFinal(data); } /**** 字节加密*/public static byte[] encrypt(byte[] data, String key) throws Exception {Key k = toKey(Base64.decode(key));byte[] raw = k.getEncoded();SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);return cipher.doFinal(data);}解密:1、在tomcat的WebappClassLoader中修改源码(自动义类加载器);2、修改spring源码Code包源码。加密方法Java代码 public static byte[] decrypt(byte[] data, String key) throws Exception { Key k = toKey(Base64.decode(key)); byte[] raw = k.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, String key) throws Exception {Key k = toKey(Base64.decode(key));byte[] raw = k.getEncoded();SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);return cipher.doFinal(data);}在 WebappClassLoader中解密Java代码 /** * 判断如需是需要解密的类进行数据处理 * */ //————————————–start———————————-// byte []data=null; try { if(isDecode(name)){ System.out.println("2818:–&&&-"+name); data=AESUtils.decrypt(entry.binaryContent, key); }else{ data=entry.binaryContent; } } catch (Exception e) { e.printStackTrace(); } try { clazz = defineClass(name, data, 0, data.length, new CodeSource(entry.codeBase, entry.certificates)); //————————————–end———————————-// /*** 判断如需是需要解密的类进行数据处理* *///————————————–start———————————-//byte []data=null;try {if(isDecode(name)){System.out.println("2818:–&&&-"+name);data=AESUtils.decrypt(entry.binaryContent, key);}else{data=entry.binaryContent;}} catch (Exception e) {e.printStackTrace();}try {clazz = defineClass(name, data, 0,data.length,new CodeSource(entry.codeBase, entry.certificates));//————————————–end———————————-//在spring的code包的SimpleMetadataReader修改器构造函数Java代码 // TODO 修改源码判断是否需要解密 SimpleMetadataReader(Resource resource, ClassLoader classLoader) throws IOException { InputStream is = resource.getInputStream(); ClassReader classReader = null; try { String name = ""; if (resource.getURI().toString().indexOf("jar:file") == -1) { name = resource.getFile().getAbsolutePath(); if (!"".equals(name) && isDecode(name, cams)) { byte[] data = inputStreamToByte(is); try { is = new ByteArrayInputStream(AESUtils.decrypt(data, key)); // is = new ByteArrayInputStream(data); } catch (Exception e) { e.printStackTrace(); } } } classReader = new ClassReader(is); } finally { is.close(); } // TODO 修改源码判断是否需要解密SimpleMetadataReader(Resource resource, ClassLoader classLoader)throws IOException {InputStream is = resource.getInputStream();ClassReader classReader = null;try {String name = "";if (resource.getURI().toString().indexOf("jar:file") == -1) {name = resource.getFile().getAbsolutePath();if (!"".equals(name) && isDecode(name, cams)) {byte[] data = inputStreamToByte(is);try {is = new ByteArrayInputStream(AESUtils.decrypt(data,key));// is = new ByteArrayInputStream(data);} catch (Exception e) {e.printStackTrace();}}}classReader = new ClassReader(is);} finally {is.close();}在同样需要进行解密。注:(此加密有弊端)1、加密解密算法需保持一致。2、加密加密密钥需是同一密钥。

8. spring+mybatis数据源密码怎样加密有没有必要

不需要加密,可以直接放置在spring配置文件中,也可以定义应用程序服务器数据源,spring利用jndi数据源

9. 在Spring中如何使用加密外部属性文件

1.jdbc.properties文件driverClassName=com.mysql.jdbc.Driverurl:jdbc:mysql://localhost:3306/testdbusername=rootpassword=12312342.xml文件引入属性文件<!– 引入配置文件 –><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfiguer"p:location="class:jdbc.preperties"p:fileEncoding="utf-8"/><!– 使用属性值 –><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"p:driverClassName="${drverClassName}"p:url="${url}"p:username="${userName}"p:password="${password}"/>12345678910113.PropertyPlaceholderConfigurer其他属性locations:配置多个配置文件(配置 list 一样)fileEncoding:编码格式order:如歌配置多个PropertyPlaceholderConfigurer,通过该属性指定优先顺序placeholderPrefix:指定占位符前缀,默认为“${”placeholderSuffix:占位符后缀,默认为“}”<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/opt/demo/config/demo-db.properties</value> <value>classpath:/opt/demo/config/demo-db2.properties</value> </list> </property> </bean> 123456784.使用”<”context:property-placeholder”>”引入属性文件//这种方式比较优雅,但如果想要配置日他额外高级属性,如属性加密,使用数据库保存配置信息等,必须使用扩展的PropertyPlaceholderConfigurer类并使用bean配置方式<context:property-placeholder location="class:jdbc.properties"/>//引入多个配置文件 逗号分隔<context:property-placeholder location="classpath:constants.properties ,classpath:constants_new.properties"fileEncoding="utf-8"/>12345678910115.在基于注解的java类配置中引用属性@Componentpublic class Test{//@Value注解可以为Bean注入一个字面量,也可通过@Value("#{proName}")形式注入值@Value("com.mysql.jdbc.Driver")private String driverClassName;@Value("${url}")private String url;}