1. 程式人生 > 其它 >寫一個自己的platEntity模組-自定義加密註解實現dao層和資料庫互動時對指定屬性進行加解密

寫一個自己的platEntity模組-自定義加密註解實現dao層和資料庫互動時對指定屬性進行加解密

技術標籤:mybatis自定義註解RSA

文章目錄

一,引入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"來動態指定(不過本模組暫時只支援RSA加密,SM4沒來得及更新上)
  2. ParamEncrypt="true/false"來指定該欄位存入到表時是否需要進行加密,預設是需要加密的
  3. resultEncrypt="true/false"來指定從表裡查出來的列表,該欄位是否需要解密,預設是需要解密的,如果為false,那麼查出來的欄位值則為密文

如果ParamEncrypt已經為false了,就不要指定resultEncrypt為true了,因為都沒有加密,所以解密肯定會報錯了!

如果有對原始碼感興趣的朋友,直接訪問下方的github地址,來一波星星吧!阿門!

原始碼地址

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