写一个自己的platEntity模块-自定义加密注解实现dao层和数据库交互时对指定属性进行加解密

一,引入platEntity模块

为什么要写一个这个模块?它的作用是什么?

有一些场景,比如新增一个用户,实体类User类

public class Test {
    private Integer id;
    private String name;
    private String account;
    private String password;
}

其中密码字段是要加密之后存储到数据库的,我们平时的操作是什么?从前台传来的password字段取出并手动进行加密,然后存入User表,取出的时候还需要进行解密,然后返回明文密码的列表。

platEntity简化了这一切加解密的过程,使用platEntity之后再也不用手动加解密,只需要一个注解就可以实现复杂的逻辑,而且使用灵活方便,可以控制加密方式,是否加密,返回的列表中的字段值是否要解密。

如何使用?

使用方式也很简单,该platEntity模块已经上传到我的私服,如果兄弟们感兴趣的话可以尝试着用一下,不好用不收钱哈!

首先在pom.xml配置私服

	<repositories>
		<repository>
			<id>maven-ossez</id>
			<name>OSSEZ Repository</name>
			<url>http://nexus.tiger2.cn/nexus/content/groups/public/</url>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>maven-ossez</id>
			<name>OSSEZ Repository</name>
			<url>http://nexus.tiger2.cn/nexus/content/groups/public/</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>

然后引入模块坐标

		<dependency>
			<groupId>com.rain.platentity</groupId>
			<artifactId>rain-platentity</artifactId>
			<version>1.2</version>
		</dependency>

最后不要忘记在启动类上方要加上包扫描,如果扫描不到也是不起作用的!配置com.rain.platentity

@ComponentScan(basePackages = {"你们自己的包位置","com.rain.platentity"})

二,使用方式

使用方式很简单,哪个实体类的哪个属性需要加密处理,就在该实体类上加一个@EncryptDecryptClass注解即可,然后在那个具体要加密的属性上加一个@EncryptDecryptField注解,就OK了!

前提:与数据库交互使用的框架是Mybatis才可使用此模块,因为用到了Mybatis拦截器!

@EncryptDecryptClass
public class Test {
    private Integer id;
    private String name;
    private String account;

    @EncryptDecryptField
    private String password;
}

其中属性注解@EncryptDecryptField的内容如下

    String type() default "RSA";

    boolean ParamEncrypt() default true;

    boolean resultEncrypt() default true;
  1. 默认加密方式是RSA,可以通过type="SM4"来动态指定
  2. ParamEncrypt="true/false"来指定该字段存入到表时是否需要进行加密,默认是需要加密的
  3. resultEncrypt="true/false"来指定从表里查出来的列表,该字段是否需要解密,默认是需要解密的,如果为false,那么查出来的字段值则为密文

如果ParamEncrypt已经为false了,就不要指定resultEncrypt为true了,因为都没有加密,所以解密肯定会报错了!

如果有对源码感兴趣的朋友,直接访问下方的github地址,来一波星星吧!阿门!(该jar已经整成了starter自动配置,引入可直接使用,无需在包扫描之类的)

源码地址

https://github.com/fantongxue666/Rain/tree/master/rain-platentity/src/main/java/com/rain/platentity

posted @ 2021-01-27 10:11  你樊不樊  阅读(45)  评论(0编辑  收藏  举报