package com.wafer.annotation;

import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.HexUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; import com.wafer.global.Const; import lombok.extern.slf4j.Slf4j;

import javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.io.UnsupportedEncodingException;

/**

  • Jpa 加密解密
  • @author tianjian */ @Converter @Slf4j public class EncryptionConverter implements AttributeConverter<String, String> {

private static String RSA_PUB_KEY = Const.RSA_PUB_KEY; private static String RSA_PRI_KEY = Const.RSA_PRI_KEY; private static RSA rsa = new RSA(RSA_PRI_KEY, RSA_PUB_KEY); /**

  • 加密
  • @param attribute
  • @return */ @Override public String convertToDatabaseColumn(String attribute) { if (StrUtil.isEmpty(attribute)) { return attribute; } // log.info("编码前2:{}",attribute); try { // RSA rsa = new RSA(Const.RSA_PRI_KEY, Const.RSA_PUB_KEY); byte[] encrypt = rsa.encrypt(StrUtil.bytes(attribute, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey); attribute = HexUtil.encodeHexStr(encrypt); // log.info("编码后2:{}",attribute); return attribute; } catch (Exception e) { log.error("编码异常", e); return attribute; } }

/**

  • 解密
  • @param dbData
  • @return */ @Override public String convertToEntityAttribute(String dbData) { if (StrUtil.isEmpty(dbData)) { return dbData; } try {

// RSA rsa = new RSA(Const.RSA_PRI_KEY, Const.RSA_PUB_KEY); byte[] decrypt = rsa.decrypt(dbData, KeyType.PrivateKey); try { dbData = new String(decrypt,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return dbData; } catch (Exception e) { log.error("解密异常", e); return dbData;

}

} }

model层增加 @Convert(converter = EncryptionConverter.class)注解即可