springboot 項目中使用 aes 在 java 與數據庫之間進行數據加密與解密


java 中常用的加密算法有 DES、IDEA、RC2、RC4、SKIPJACK、RC5、AES 算法等。AES 加密算法在處理效率、安全性等方面綜合性較好,單密鑰處理起來也比較方便,下文主要針對 AES 來展開闡述。

AES 算法簡介

AES 技術是一種對稱的分組加密技術,使用 128 位分組加密數據,提供比 WEP/TKIPS 的 RC4 算法更高的加密強度。AES 的加密碼表和解密碼表是分開的,並且支持子密鑰加密,這種做法優於以前用一個特殊的密鑰解密的做法。AES 算法支持任意分組大小,初始時間快。特別是它具有的並行性可以有效地利用處理器資源。

AES 具有應用范圍廣、等待時間短、相對容易隱藏、吞吐量高等優點,在性能等各方面都優於 WEP 算法。利用此算法加密,WLAN 的安全性將會獲得大幅度提高。AES 算法已經在 802.11i 標准中得到最終確認,成為取代 WEP 的新一代的加密算法。但是由於 AES 算法對硬件要求比較高,因此 AES 無法通過在原有設備上升級固件實現,必須重新設計芯片。

場景

先說一下應用場景:

  • 寫入:Java 中正常可讀的 bean,加密后寫入關系型數據庫,數據庫中僅存儲密文;
  • 讀取:java 內通過 jdbc 讀取關系型數據庫中的密文,解密后轉為相應的 bean 供給其它服務使用;

手動在 java 和數據庫交互加一個加密與解密的服務可以滿足該場景的要求,但是作為一個喜歡偷懶的人不喜歡這種解決方案。查詢了一堆資料后發現屬性轉換類javax.persistence.AttributeConverter可用於業務對象屬性轉換上,在轉換方法內部寫如加密和解密算法剛好可以解決該場景的要求。網上提供的使用AttributeConverter來進行類型轉換的方案中,業務層多使用的是 jpa,目前沒有找到使用 mybatis 的方案。下面詳細介紹下具體實施方法。

加密工具類

AES 加密工具類來源與博客https://blog.csdn.net/SpiderManSun/article/details/84942010

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;

public class AESUtil {
    /**
     * 秘鑰:請勿修改
     */
    public static String key = "%%%*^@&^(!&$%^$(*((*sad131fe21";
    /**
     * AES加密
     *
     * @param plaintext   明文
     * @param Key         密鑰
     * @param EncryptMode AES加密模式,CBC或ECB
     * @return 該字符串的AES密文值
     */
    public static String AESEncrypt(Object plaintext, String Key, String EncryptMode) {
        String PlainText = null;
        try {
            PlainText = plaintext.toString();
            if (Key == null) {
                return null;
            }
            Key = getMD5(Key);
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/" + EncryptMode + "/PKCS5Padding");
            if (EncryptMode == "ECB") {
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            } else {
                IvParameterSpec iv = new IvParameterSpec(Key.getBytes("utf-8"));//使用CBC模式,需要一個向量iv,可增加加密算法的強度
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted = cipher.doFinal(PlainText.getBytes("utf-8"));
            String encryptedStr = new String(new BASE64Encoder().encode(encrypted));
            return encryptedStr;
            //return new String(encrypted);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * AES解密
     *
     * @param cipertext   密文
     * @param Key         密鑰
     * @param EncryptMode AES加密模式,CBC或ECB
     * @return 該密文的明文
     */
    public static String AESDecrypt(Object cipertext, String Key, String EncryptMode) {
        String CipherText = null;
        try {
            CipherText = cipertext.toString();
            // 判斷Key是否正確
            if (Key == null) {
                //System.out.print("Key為空null");
                return null;
            }
            Key = getMD5(Key);
            byte[] raw = Key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/" + EncryptMode + "/PKCS5Padding");
            if (EncryptMode == "ECB") {
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            } else {
                IvParameterSpec iv = new IvParameterSpec(Key.getBytes("utf-8"));//使用CBC模式,需要一個向量iv,可增加加密算法的強度
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(CipherText);//先用base64解密
            //byte[] encrypted1 = CipherText.getBytes();
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * 進行MD5加密
     *
     * @param s 要進行MD5轉換的字符串
     * @return 該字符串的MD5值的8-24位
     */
    public static String getMD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        try {
            byte[] btInput = s.getBytes();
            // 獲得MD5摘要算法的 MessageDigest 對象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字節更新摘要
            mdInst.update(btInput);
            // 獲得密文
            byte[] md = mdInst.digest();
            // 把密文轉換成十六進制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).substring(8, 24);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

類中的私有變量 key 為 AES 密鑰,一般可以視情況找地方存放。

屬性類型轉換器

  • double 類型加密
import jdk.nashorn.internal.runtime.regexp.joni.exception.ValueException;

import javax.persistence.AttributeConverter;

public class DoubleFStringEncryptConverter implements AttributeConverter<Double, String> {

    @Override
    public String convertToDatabaseColumn(Double attribute) {
        return AESUtil.AESEncrypt(attribute, AESUtil.key, "CBC");
    }

    @Override
    public Double convertToEntityAttribute(String dbData) {
        String tmp = AESUtil.AESDecrypt(dbData, AESUtil.key, "CBC");
        Double value = Double.valueOf(-1);
        try {
            value = Double.valueOf(tmp);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ValueException("字符串轉換為浮點數失敗");
        }
        return value;
    }
}

  • int 類型加密
import jdk.nashorn.internal.runtime.regexp.joni.exception.ValueException;

import javax.persistence.AttributeConverter;

public class IntegerFStringEncryptConverter implements AttributeConverter<Integer, String> {

    @Override
    public String convertToDatabaseColumn(Integer attribute) {
        return AESUtil.AESEncrypt(attribute, AESUtil.key, "CBC");
    }

    @Override
    public Integer convertToEntityAttribute(String dbData) {
        String tmp = AESUtil.AESDecrypt(dbData, AESUtil.key, "CBC");
        Integer value = Integer.valueOf(-1);
        try {
            value = Integer.valueOf(tmp);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ValueException("字符串轉換為整數失敗");
        }
        return value;
    }
}
  • String 類型加密
import javax.persistence.AttributeConverter;

public class StringFStringEncryptConverter implements AttributeConverter<String, String> {
    @Override
    public String convertToDatabaseColumn(String attribute) {
        return AESUtil.AESEncrypt(attribute, AESUtil.key, "CBC");
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        return AESUtil.AESDecrypt(dbData, AESUtil.key, "CBC");
    }
}

轉換器在 Entity 中的使用

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

@Data
@Entity
@Table(name = "t_test")
public class CityBaseInfoPo implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private Integer id;

    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "city_id")
    private String cityId;

    @Column(name = "angle")
    @Convert(converter = DoubleFStringEncryptConverter.class)
    private double angle;

    @Column(name = "height_above_sea")
    @Convert(converter = DoubleFStringEncryptConverter.class)
    private double heightAboveSea;

    @Column(name = "latitude")
    @Convert(converter = DoubleFStringEncryptConverter.class)
    private double latitude;

    @Column(name = "longitude")
    @Convert(converter = DoubleFStringEncryptConverter.class)
    private double longitude;
}

加密效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM