自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Mybatis自定義類型轉換,數(shù)據(jù)加密解密全攻略【實戰(zhàn)】

開發(fā) 前端
數(shù)據(jù)加密解密則可以提高數(shù)據(jù)的安全性,保護敏感信息不被泄露。在MyBatis中,你可以使用類型處理器(TypeHandler)來實現(xiàn)自定義類型轉換,使用加密和解密算法來實現(xiàn)數(shù)據(jù)加密解密。

環(huán)境:springboot2.6.12 + MyBatis3.5.6 + MySQL

MyBatis是一種優(yōu)秀的持久層框架,它支持自定義類型轉換和數(shù)據(jù)加密解密。通過自定義類型轉換,你可以輕松地將數(shù)據(jù)庫中的數(shù)據(jù)類型轉換為Java對象中的數(shù)據(jù)類型,以及將Java對象中的數(shù)據(jù)類型轉換為數(shù)據(jù)庫中的數(shù)據(jù)類型。而數(shù)據(jù)加密解密則可以提高數(shù)據(jù)的安全性,保護敏感信息不被泄露。在MyBatis中,你可以使用類型處理器(TypeHandler)來實現(xiàn)自定義類型轉換,使用加密和解密算法來實現(xiàn)數(shù)據(jù)加密解密。

本案例使用自定義類型轉換器對數(shù)據(jù)列進行加解密

1. 依賴及相關配置

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
  </dependency>
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.0</version>
  </dependency>
</dependencies>
spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/testjpa?serverTimezone=GMT%2B8
    username: root
    password: xxxxx
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      minimumIdle: 10
      maximumPoolSize: 200
      autoCommit: true
      idleTimeout: 30000
      poolName: MasterDatabookHikariCP
      maxLifetime: 1800000
      connectionTimeout: 30000
      connectionTestQuery: SELECT 1
---
spring:
  jpa:
    generateDdl: false
    hibernate:
      ddlAuto: update
    openInView: true
    show-sql: true
---
pagehelper:
  helperDialect: mysql
  reasonable: true
  pageSizeZero: true
  offsetAsPageNum: true
  rowBoundsWithCount: true
---
mybatis:
  type-aliases-package: com.pack.domain
  mapper-locations:
  - classpath:/mappers/*.xml
  configuration:
    lazy-loading-enabled: true
    aggressive-lazy-loading: false
---
logging:
  level:
    com.pack.mapper: debug

實體對象

@Entity
@Table(name = "BC_PERSON")
public class Person extends BaseEntity {
  private String name ;
  private String idNo ;
}

這里是用JPA來幫助我們生成數(shù)據(jù)表。

2. 自定義類型轉換器及數(shù)據(jù)加解密工具

public class EncryptTypeHandler implements TypeHandler<String> {
  @Override
  public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, EncryptUtils.encrypt(parameter)) ;
  }
  @Override
  public String getResult(ResultSet rs, String columnName) throws SQLException {
    String value = rs.getString(columnName) ;
    if (value == null || value.length() == 0) {
      return null ;
    }
    return EncryptUtils.decrypt(value);
  }


  @Override
  public String getResult(ResultSet rs, int columnIndex) throws SQLException {
    String value = rs.getString(columnIndex) ;
    if (value == null || value.length() == 0) {
      return null ;
    }
    return EncryptUtils.decrypt(value);
  }


  @Override
  public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
    String value = cs.getString(columnIndex) ;
    if (value == null || value.length() == 0) {
      return null ;
    }
    return EncryptUtils.decrypt(value);
  }
}

加解密工具類

public class EncryptUtils {


  private static final String secretKey = "1111222244445555" ;
  private static final String ALGORITHM  = "AES" ;


  public static String encrypt(String data) {
    try {
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding") ;
      cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretKey.getBytes(), ALGORITHM)) ;
      return Hex.encode(cipher.doFinal(data.getBytes())) ;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
      e.printStackTrace();
      return null ;
    }
  }


  public static String decrypt(String secretText) {
    try {
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding") ;
      cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getBytes(), ALGORITHM)) ;
      return new String(cipher.doFinal(Hex.decode(secretText))) ;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
      e.printStackTrace();
      return null ;
    }
  }


  private static class Hex {


    private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };


    public static byte[] decode(CharSequence s) {
      int nChars = s.length();
      if (nChars % 2 != 0) {
        throw new IllegalArgumentException("16進制數(shù)據(jù)錯誤");
      }
      byte[] result = new byte[nChars / 2];
      for (int i = 0; i < nChars; i += 2) {
        int msb = Character.digit(s.charAt(i), 16);
        int lsb = Character.digit(s.charAt(i + 1), 16);
        if (msb < 0 || lsb < 0) {
          throw new IllegalArgumentException("Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");
        }
        result[i / 2] = (byte) ((msb << 4) | lsb);
      }
      return result;
    }


    public static String encode(byte[] buf) {
      StringBuilder sb = new StringBuilder() ;
      for (int i = 0, leng = buf.length; i < leng; i++) {
        sb.append(HEX[(buf[i] & 0xF0) >>> 4]).append(HEX[buf[i] & 0x0F]) ;
      }
      return sb.toString() ;
    }


  }


}

Mapper及XML文件

@Mapper
public interface PersonMapper {
  List<Person> queryPersons() ;


  int insertPerson(Person person) ;
}
<mapper namespace="com.pack.mapper.PersonMapper">
  <resultMap type="com.pack.domain.Person" id="PersonMap">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="id_no" property="idNo" typeHandler="com.pack.mybatis.EncryptTypeHandler"/>
    <result column="create_time" property="createTime"/>
  </resultMap>
  <select id="queryPersons" resultMap="PersonMap">
    SELECT * FROM bc_person
  </select>
  <insert id="insertPerson" parameterType="com.pack.domain.Person">
    insert into bc_person (id, name, id_no, create_time) values (#{id}, #{name}, #{idNo, typeHandler=com.pack.mybatis.EncryptTypeHandler}, #{createTime})
  </insert>
</mapper>

查詢數(shù)據(jù)時在resultMap中的result中配置typeHandler="com.pack.mybatis.EncryptTypeHandler",指明該列的類型轉換。

在insert中對具體的列進行指明類型轉換。

3. 測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootComprehensiveApplicationTests {


  @Resource
  private PersonMapper personMapper ;
  @Test
  public void testInsertMapper() {
    com.pack.domain.Person person = new com.pack.domain.Person() ;
    person.setId("0001") ;
    person.setCreateTime(new Date()) ;
    person.setIdNo("111111") ;
    person.setName("中國") ;
    personMapper.insertPerson(person) ;
  }
  @Test
  public void testQueryUers() {
    System.out.println(personMapper.queryPersons()) ;
  }
}

圖片圖片

插入數(shù)據(jù)時數(shù)據(jù)已經(jīng)被我們自定義的類型轉換器進行了加密處理。

圖片圖片

查詢數(shù)據(jù)進行了解密處理。

完畢?。?!

責任編輯:武曉燕 來源: Spring全家桶實戰(zhàn)案例源碼
相關推薦

2015-03-04 13:53:33

MySQL數(shù)據(jù)庫優(yōu)化SQL優(yōu)化

2013-06-08 11:13:00

Android開發(fā)XML解析

2013-04-15 10:48:16

Xcode ARC詳解iOS ARC使用

2024-05-07 09:01:21

Queue 模塊Python線程安全隊列

2022-06-20 08:26:39

Spring容器類型轉換

2010-04-23 14:04:23

Oracle日期操作

2021-04-23 20:59:02

ThreadLocal內(nèi)存

2014-03-19 17:22:33

2009-12-14 14:32:38

動態(tài)路由配置

2009-10-19 15:20:01

家庭綜合布線

2009-02-20 11:43:22

UNIXfish全攻略

2009-08-12 14:53:50

C#類型轉換函數(shù)

2009-12-17 16:15:00

CCNA640-810

2010-08-25 14:36:02

DHCP服務器

2019-06-27 11:47:21

Wordpress容器化HTTPS

2024-10-25 15:25:42

2020-11-23 15:21:12

Linux環(huán)境變量

2009-02-12 10:12:00

NAT配置

2009-07-17 17:43:49

Jruby開發(fā)Web

2009-11-10 12:08:15

點贊
收藏

51CTO技術棧公眾號