可以对数据加密,解密,对数据库加密的数据进行解密显示,对数据库没有加密的数据进行加密处理展示前端等待
1:引入数据如下结构
1-1:SensitiveDecode脱敏解密注解
package com. example. poi. desensitization. annotation ;
import java. lang. annotation. * ;
@Documented
@Retention ( RetentionPolicy . RUNTIME )
@Target ( { ElementType . METHOD } )
public @interface SensitiveDecode {
Class entity ( ) default Object . class ;
}
1-2:SensitiveEncode脱敏加密注解
package com. example. poi. desensitization. annotation ;
import java. lang. annotation. * ;
@Documented
@Retention ( RetentionPolicy . RUNTIME )
@Target ( { ElementType . METHOD } )
public @interface SensitiveEncode {
Class entity ( ) default Object . class ;
}
1-3:SensitiveField字段注解
package com. example. poi. desensitization. annotation ;
import com. example. poi. desensitization. enums. SensitiveEnum ;
import java. lang. annotation. * ;
@Documented
@Retention ( RetentionPolicy . RUNTIME )
@Target ( ElementType . FIELD )
public @interface SensitiveField {
SensitiveEnum type ( ) default SensitiveEnum . ENCODE ;
}
1-4:SensitiveDataAspect敏感数据切面处理类
package com. example. poi. desensitization. aspect ;
import com. example. poi. desensitization. annotation. SensitiveDecode ;
import com. example. poi. desensitization. annotation. SensitiveEncode ;
import com. example. poi. desensitization. utils. SensitiveInfoUtil ;
import lombok. extern. slf4j. Slf4j ;
import org. aspectj. lang. ProceedingJoinPoint ;
import org. aspectj. lang. annotation. Around ;
import org. aspectj. lang. annotation. Aspect ;
import org. aspectj. lang. annotation. Pointcut ;
import org. aspectj. lang. reflect. MethodSignature ;
import org. springframework. stereotype. Component ;
import java. lang. reflect. Method ;
import java. util. List ;
@Slf4j
@Aspect
@Component
public class SensitiveDataAspect {
@Pointcut ( "@annotation(com.example.poi.desensitization.annotation.SensitiveEncode) || @annotation(com.example.poi.desensitization.annotation.SensitiveDecode)" )
public void sensitivePointCut ( ) {
}
@Around ( "sensitivePointCut()" )
public Object around ( ProceedingJoinPoint point) throws Throwable {
Object result = point. proceed ( ) ;
if ( result == null ) {
return result;
}
Class resultClass = result. getClass ( ) ;
log. debug ( " resultClass = {}" , resultClass) ;
if ( resultClass. isPrimitive ( ) ) {
return result;
}
boolean isEncode = true ;
Class entity = null ;
MethodSignature methodSignature = ( MethodSignature ) point. getSignature ( ) ;
Method method = methodSignature. getMethod ( ) ;
SensitiveEncode encode = method. getAnnotation ( SensitiveEncode . class ) ;
if ( encode== null ) {
SensitiveDecode decode = method. getAnnotation ( SensitiveDecode . class ) ;
if ( decode!= null ) {
entity = decode. entity ( ) ;
isEncode = false ;
}
} else {
entity = encode. entity ( ) ;
}
long startTime= System . currentTimeMillis ( ) ;
if ( resultClass. equals ( entity) || entity. equals ( Object . class ) ) {
SensitiveInfoUtil . handlerObject ( result, isEncode) ;
} else if ( result instanceof List ) {
SensitiveInfoUtil . handleList ( result, entity, isEncode) ;
} else {
SensitiveInfoUtil . handleNestedObject ( result, entity, isEncode) ;
}
long endTime= System . currentTimeMillis ( ) ;
log. info ( ( isEncode ? "加密操作," : "解密操作," ) + "Aspect程序耗时:" + ( endTime - startTime) + "ms" ) ;
return result;
}
}
1-5:SensitiveEnum
package com. example. poi. desensitization. enums ;
public enum SensitiveEnum {
ENCODE ,
CHINESE_NAME ,
ID_CARD ,
FIXED_PHONE ,
MOBILE_PHONE ,
ADDRESS ,
EMAIL ,
BANK_CARD ,
CNAPS_CODE ;
}
1-6:AesEncryptUtil加密工具类
package com. example. poi. desensitization. utils. encryption ;
import cn. hutool. core. codec. Base64 ;
import cn. hutool. crypto. SecureUtil ;
import javax. crypto. Cipher ;
import javax. crypto. spec. IvParameterSpec ;
import javax. crypto. spec. SecretKeySpec ;
public class AesEncryptUtil {
private static String KEY = EncryptedString . key;
private static String IV = EncryptedString . iv;
public static String encrypt ( String data, String key, String iv) throws Exception {
try {
Cipher cipher = Cipher . getInstance ( "AES/CBC/NoPadding" ) ;
int blockSize = cipher. getBlockSize ( ) ;
byte [ ] dataBytes = data. getBytes ( ) ;
int plaintextLength = dataBytes. length;
if ( plaintextLength % blockSize != 0 ) {
plaintextLength = plaintextLength + ( blockSize - ( plaintextLength % blockSize) ) ;
}
byte [ ] plaintext = new byte [ plaintextLength] ;
System . arraycopy ( dataBytes, 0 , plaintext, 0 , dataBytes. length) ;
SecretKeySpec keyspec = new SecretKeySpec ( key. getBytes ( ) , "AES" ) ;
IvParameterSpec ivspec = new IvParameterSpec ( iv. getBytes ( ) ) ;
cipher. init ( Cipher . ENCRYPT_MODE , keyspec, ivspec) ;
byte [ ] encrypted = cipher. doFinal ( plaintext) ;
return Base64 . encode ( encrypted) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
return null ;
}
}
public static String desEncrypt ( String data, String key, String iv) throws Exception {
byte [ ] encrypted1 = Base64 . decode ( data) ;
Cipher cipher = Cipher . getInstance ( "AES/CBC/NoPadding" ) ;
SecretKeySpec keyspec = new SecretKeySpec ( key. getBytes ( ) , "AES" ) ;
IvParameterSpec ivspec = new IvParameterSpec ( iv. getBytes ( ) ) ;
cipher. init ( Cipher . DECRYPT_MODE , keyspec, ivspec) ;
byte [ ] original = cipher. doFinal ( encrypted1) ;
String originalString = new String ( original) ;
return originalString. replaceAll ( "\\u0000" , "" ) ;
}
public static String encrypt ( String data) throws Exception {
return encrypt ( data, KEY , IV ) ;
}
public static String desEncrypt ( String data) throws Exception {
return desEncrypt ( data, KEY , IV ) ;
}
public static void main ( String args[ ] ) throws Exception {
String test1 = "sa" ;
String test = new String ( test1. getBytes ( ) , "UTF-8" ) ;
String data = "4I80+jJsZ/aR+n+MsRd7qw==" ;
String key = KEY ;
String iv = IV ;
String jiemi = desEncrypt ( data, key, iv) . trim ( ) ;
System . out. println ( "解密:" + jiemi) ;
String aa= "1234567897891" ;
String encrypt = SecureUtil . aes ( key. getBytes ( ) ) . encryptBase64 ( aa) ;
String s = SecureUtil . aes ( key. getBytes ( ) ) . decryptStr ( encrypt) ;
System . out. println ( "" ) ;
}
}
1-7:EncryptedString
package com. example. poi. desensitization. utils. encryption ;
import lombok. Data ;
@Data
public class EncryptedString {
public static String key = "1234567890adbcde" ;
public static String iv = "1234567890hjlkew" ;
}
1-8:CommonConstant通用常量
package com. example. poi. desensitization. utils ;
public interface CommonConstant {
String UNKNOWN = "unknown" ;
String STRING_NULL = "null" ;
}
1-9:oConvertUtils
package com. example. poi. desensitization. utils ;
import lombok. extern. slf4j. Slf4j ;
import org. apache. commons. io. IOUtils ;
import org. springframework. beans. BeanUtils ;
import javax. servlet. http. HttpServletRequest ;
import java. io. IOException ;
import java. io. InputStream ;
import java. io. UnsupportedEncodingException ;
import java. lang. reflect. Field ;
import java. math. BigDecimal ;
import java. math. BigInteger ;
import java. net. InetAddress ;
import java. net. NetworkInterface ;
import java. net. SocketException ;
import java. net. UnknownHostException ;
import java. sql. Date ;
import java. util. * ;
import java. util. regex. Matcher ;
import java. util. regex. Pattern ;
@Slf4j
public class oConvertUtils {
public static boolean isEmpty ( Object object) {
if ( object == null ) {
return ( true ) ;
}
if ( "" . equals ( object) ) {
return ( true ) ;
}
if ( CommonConstant . STRING_NULL . equals ( object) ) {
return ( true ) ;
}
return ( false ) ;
}
public static boolean isNotEmpty ( Object object) {
if ( object != null && ! "" . equals ( object) && ! object. equals ( CommonConstant . STRING_NULL ) ) {
return ( true ) ;
}
return ( false ) ;
}
public static String decode ( String strIn, String sourceCode, String targetCode) {
String temp = code2code ( strIn, sourceCode, targetCode) ;
return temp;
}
@SuppressWarnings ( "AlibabaLowerCamelCaseVariableNaming" )
public static String StrToUTF ( String strIn, String sourceCode, String targetCode) {
strIn = "" ;
try {
strIn = new String ( strIn. getBytes ( "ISO-8859-1" ) , "GBK" ) ;
} catch ( UnsupportedEncodingException e) {
e. printStackTrace ( ) ;
}
return strIn;
}
private static String code2code ( String strIn, String sourceCode, String targetCode) {
String strOut = null ;
if ( strIn == null || "" . equals ( strIn. trim ( ) ) ) {
return strIn;
}
try {
byte [ ] b = strIn. getBytes ( sourceCode) ;
for ( int i = 0 ; i < b. length; i++ ) {
System . out. print ( b[ i] + " " ) ;
}
strOut = new String ( b, targetCode) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
return null ;
}
return strOut;
}
public static int getInt ( String s, int defval) {
if ( s == null || s == "" ) {
return ( defval) ;
}
try {
return ( Integer . parseInt ( s) ) ;
} catch ( NumberFormatException e) {
return ( defval) ;
}
}
public static int getInt ( String s) {
if ( s == null || s == "" ) {
return 0 ;
}
try {
return ( Integer . parseInt ( s) ) ;
} catch ( NumberFormatException e) {
return 0 ;
}
}
public static int getInt ( String s, Integer df) {
if ( s == null || s == "" ) {
return df;
}
try {
return ( Integer . parseInt ( s) ) ;
} catch ( NumberFormatException e) {
return 0 ;
}
}
public static Integer [ ] getInts ( String [ ] s) {
if ( s == null ) {
return null ;
}
Integer [ ] integer = new Integer [ s. length] ;
for ( int i = 0 ; i < s. length; i++ ) {
integer[ i] = Integer . parseInt ( s[ i] ) ;
}
return integer;
}
public static double getDouble ( String s, double defval) {
if ( s == null || s == "" ) {
return ( defval) ;
}
try {
return ( Double . parseDouble ( s) ) ;
} catch ( NumberFormatException e) {
return ( defval) ;
}
}
public static double getDou ( Double s, double defval) {
if ( s == null ) {
return ( defval) ;
}
return s;
}
public static int getInt ( Object object, int defval) {
if ( isEmpty ( object) ) {
return ( defval) ;
}
try {
return ( Integer . parseInt ( object. toString ( ) ) ) ;
} catch ( NumberFormatException e) {
return ( defval) ;
}
}
public static Integer getInt ( Object object) {
if ( isEmpty ( object) ) {
return null ;
}
try {
return ( Integer . parseInt ( object. toString ( ) ) ) ;
} catch ( NumberFormatException e) {
return null ;
}
}
public static int getInt ( BigDecimal s, int defval) {
if ( s == null ) {
return ( defval) ;
}
return s. intValue ( ) ;
}
public static Integer [ ] getIntegerArry ( String [ ] object) {
int len = object. length;
Integer [ ] result = new Integer [ len] ;
try {
for ( int i = 0 ; i < len; i++ ) {
result[ i] = new Integer ( object[ i] . trim ( ) ) ;
}
return result;
} catch ( NumberFormatException e) {
return null ;
}
}
public static String getString ( String s) {
return ( getString ( s, "" ) ) ;
}
public static String getString ( Object object) {
if ( isEmpty ( object) ) {
return "" ;
}
return ( object. toString ( ) . trim ( ) ) ;
}
public static String getString ( int i) {
return ( String . valueOf ( i) ) ;
}
public static String getString ( float i) {
return ( String . valueOf ( i) ) ;
}
public static String getString ( String s, String defval) {
if ( isEmpty ( s) ) {
return ( defval) ;
}
return ( s. trim ( ) ) ;
}
public static String getString ( Object s, String defval) {
if ( isEmpty ( s) ) {
return ( defval) ;
}
return ( s. toString ( ) . trim ( ) ) ;
}
public static long stringToLong ( String str) {
Long test = new Long ( 0 ) ;
try {
test = Long . valueOf ( str) ;
} catch ( Exception e) {
}
return test. longValue ( ) ;
}
public static String getIp ( ) {
String ip = null ;
try {
InetAddress address = InetAddress . getLocalHost ( ) ;
ip = address. getHostAddress ( ) ;
} catch ( UnknownHostException e) {
e. printStackTrace ( ) ;
}
return ip;
}
private static boolean isBaseDataType ( Class clazz) throws Exception {
return ( clazz. equals ( String . class ) || clazz. equals ( Integer . class ) || clazz. equals ( Byte . class ) || clazz. equals ( Long . class ) || clazz. equals ( Double . class ) || clazz. equals ( Float . class ) || clazz. equals ( Character . class ) || clazz. equals ( Short . class ) || clazz. equals ( BigDecimal . class ) || clazz. equals ( BigInteger . class ) || clazz. equals ( Boolean . class ) || clazz. equals ( Date . class ) || clazz. isPrimitive ( ) ) ;
}
public static String getIpAddrByRequest ( HttpServletRequest request) {
String ip = request. getHeader ( "x-forwarded-for" ) ;
if ( ip == null || ip. length ( ) == 0 || CommonConstant . UNKNOWN . equalsIgnoreCase ( ip) ) {
ip = request. getHeader ( "Proxy-Client-IP" ) ;
}
if ( ip == null || ip. length ( ) == 0 || CommonConstant . UNKNOWN . equalsIgnoreCase ( ip) ) {
ip = request. getHeader ( "WL-Proxy-Client-IP" ) ;
}
if ( ip == null || ip. length ( ) == 0 || CommonConstant . UNKNOWN . equalsIgnoreCase ( ip) ) {
ip = request. getRemoteAddr ( ) ;
}
return ip;
}
public static String getRealIp ( ) throws SocketException {
String localip = null ;
String netip = null ;
Enumeration < NetworkInterface > netInterfaces = NetworkInterface . getNetworkInterfaces ( ) ;
InetAddress ip = null ;
boolean finded = false ;
while ( netInterfaces. hasMoreElements ( ) && ! finded) {
NetworkInterface ni = netInterfaces. nextElement ( ) ;
Enumeration < InetAddress > address = ni. getInetAddresses ( ) ;
while ( address. hasMoreElements ( ) ) {
ip = address. nextElement ( ) ;
if ( ! ip. isSiteLocalAddress ( ) && ! ip. isLoopbackAddress ( ) && ip. getHostAddress ( ) . indexOf ( ":" ) == - 1 ) {
netip = ip. getHostAddress ( ) ;
finded = true ;
break ;
} else if ( ip. isSiteLocalAddress ( ) && ! ip. isLoopbackAddress ( ) && ip. getHostAddress ( ) . indexOf ( ":" ) == - 1 ) {
localip = ip. getHostAddress ( ) ;
}
}
}
if ( netip != null && ! "" . equals ( netip) ) {
return netip;
} else {
return localip;
}
}
public static String replaceBlank ( String str) {
String dest = "" ;
if ( str != null ) {
String reg = "\\s*|\t|\r|\n" ;
Pattern p = Pattern . compile ( reg) ;
Matcher m = p. matcher ( str) ;
dest = m. replaceAll ( "" ) ;
}
return dest;
}
public static boolean isIn ( String substring, String [ ] source) {
if ( source == null || source. length == 0 ) {
return false ;
}
for ( int i = 0 ; i < source. length; i++ ) {
String aSource = source[ i] ;
if ( aSource. equals ( substring) ) {
return true ;
}
}
return false ;
}
public static Map < Object , Object > getHashMap ( ) {
return new HashMap < > ( 5 ) ;
}
public static Map < Object , Object > setToMap ( Set < Object > setobj) {
Map < Object , Object > map = getHashMap ( ) ;
for ( Iterator iterator = setobj. iterator ( ) ; iterator. hasNext ( ) ; ) {
Map. Entry < Object , Object > entry = ( Map. Entry < Object , Object > ) iterator. next ( ) ;
map. put ( entry. getKey ( ) . toString ( ) , entry. getValue ( ) == null ? "" : entry. getValue ( ) . toString ( ) . trim ( ) ) ;
}
return map;
}
public static boolean isInnerIp ( String ipAddress) {
boolean isInnerIp = false ;
long ipNum = getIpNum ( ipAddress) ;
long aBegin = getIpNum ( "10.0.0.0" ) ;
long aEnd = getIpNum ( "10.255.255.255" ) ;
long bBegin = getIpNum ( "172.16.0.0" ) ;
long bEnd = getIpNum ( "172.31.255.255" ) ;
long cBegin = getIpNum ( "192.168.0.0" ) ;
long cEnd = getIpNum ( "192.168.255.255" ) ;
String localIp = "127.0.0.1" ;
isInnerIp = isInner ( ipNum, aBegin, aEnd) || isInner ( ipNum, bBegin, bEnd) || isInner ( ipNum, cBegin, cEnd) || localIp. equals ( ipAddress) ;
return isInnerIp;
}
private static long getIpNum ( String ipAddress) {
String [ ] ip = ipAddress. split ( "\\." ) ;
long a = Integer . parseInt ( ip[ 0 ] ) ;
long b = Integer . parseInt ( ip[ 1 ] ) ;
long c = Integer . parseInt ( ip[ 2 ] ) ;
long d = Integer . parseInt ( ip[ 3 ] ) ;
long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
return ipNum;
}
private static boolean isInner ( long userIp, long begin, long end) {
return ( userIp >= begin) && ( userIp <= end) ;
}
public static String camelName ( String name) {
StringBuilder result = new StringBuilder ( ) ;
if ( name == null || name. isEmpty ( ) ) {
return "" ;
} else if ( ! name. contains ( SymbolConstant . UNDERLINE ) ) {
return name. substring ( 0 , 1 ) . toLowerCase ( ) + name. substring ( 1 ) . toLowerCase ( ) ;
}
String [ ] camels = name. split ( "_" ) ;
for ( String camel : camels) {
if ( camel. isEmpty ( ) ) {
continue ;
}
if ( result. length ( ) == 0 ) {
result. append ( camel. toLowerCase ( ) ) ;
} else {
result. append ( camel. substring ( 0 , 1 ) . toUpperCase ( ) ) ;
result. append ( camel. substring ( 1 ) . toLowerCase ( ) ) ;
}
}
return result. toString ( ) ;
}
public static String camelNames ( String names) {
if ( names== null || "" . equals ( names) ) {
return null ;
}
StringBuffer sf = new StringBuffer ( ) ;
String [ ] fs = names. split ( "," ) ;
for ( String field : fs) {
field = camelName ( field) ;
sf. append ( field + "," ) ;
}
String result = sf. toString ( ) ;
return result. substring ( 0 , result. length ( ) - 1 ) ;
}
public static String camelNameCapFirst ( String name) {
StringBuilder result = new StringBuilder ( ) ;
if ( name == null || name. isEmpty ( ) ) {
return "" ;
} else if ( ! name. contains ( SymbolConstant . UNDERLINE ) ) {
return name. substring ( 0 , 1 ) . toUpperCase ( ) + name. substring ( 1 ) . toLowerCase ( ) ;
}
String [ ] camels = name. split ( "_" ) ;
for ( String camel : camels) {
if ( camel. isEmpty ( ) ) {
continue ;
}
result. append ( camel. substring ( 0 , 1 ) . toUpperCase ( ) ) ;
result. append ( camel. substring ( 1 ) . toLowerCase ( ) ) ;
}
return result. toString ( ) ;
}
public static String camelToUnderline ( String para) {
int length = 3 ;
if ( para. length ( ) < length) {
return para. toLowerCase ( ) ;
}
StringBuilder sb= new StringBuilder ( para) ;
int temp= 0 ;
for ( int i= 2 ; i< para. length ( ) ; i++ ) {
if ( Character . isUpperCase ( para. charAt ( i) ) ) {
sb. insert ( i+ temp, "_" ) ;
temp+= 1 ;
}
}
return sb. toString ( ) . toLowerCase ( ) ;
}
public static String randomGen ( int place) {
String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789" ;
StringBuffer sb = new StringBuffer ( ) ;
Random rd = new Random ( ) ;
for ( int i= 0 ; i< place; i++ ) {
sb. append ( base. charAt ( rd. nextInt ( base. length ( ) ) ) ) ;
}
return sb. toString ( ) ;
}
public static Field [ ] getAllFields ( Object object) {
Class < ? > clazz = object. getClass ( ) ;
List < Field > fieldList = new ArrayList < > ( ) ;
while ( clazz != null ) {
fieldList. addAll ( new ArrayList < > ( Arrays . asList ( clazz. getDeclaredFields ( ) ) ) ) ;
clazz = clazz. getSuperclass ( ) ;
}
Field [ ] fields = new Field [ fieldList. size ( ) ] ;
fieldList. toArray ( fields) ;
return fields;
}
public static List < Map < String , Object > > toLowerCasePageList ( List < Map < String , Object > > list) {
List < Map < String , Object > > select = new ArrayList < > ( ) ;
for ( Map < String , Object > row : list) {
Map < String , Object > resultMap = new HashMap < > ( 5 ) ;
Set < String > keySet = row. keySet ( ) ;
for ( String key : keySet) {
String newKey = key. toLowerCase ( ) ;
resultMap. put ( newKey, row. get ( key) ) ;
}
select. add ( resultMap) ;
}
return select;
}
public static < F , T > List < T > entityListToModelList ( List < F > fromList, Class < T > tClass) {
if ( fromList == null || fromList. isEmpty ( ) ) {
return null ;
}
List < T > tList = new ArrayList < > ( ) ;
for ( F f : fromList) {
T t = entityToModel ( f, tClass) ;
tList. add ( t) ;
}
return tList;
}
public static < F , T > T entityToModel ( F entity, Class < T > modelClass) {
log. debug ( "entityToModel : Entity属性的值赋值到Model" ) ;
Object model = null ;
if ( entity == null || modelClass == null ) {
return null ;
}
try {
model = modelClass. newInstance ( ) ;
} catch ( InstantiationException e) {
log. error ( "entityToModel : 实例化异常" , e) ;
} catch ( IllegalAccessException e) {
log. error ( "entityToModel : 安全权限异常" , e) ;
}
BeanUtils . copyProperties ( entity, model) ;
return ( T ) model;
}
public static boolean listIsEmpty ( Collection list) {
return ( list == null || list. size ( ) == 0 ) ;
}
public static boolean listIsNotEmpty ( Collection list) {
return ! listIsEmpty ( list) ;
}
public static String readStatic ( String url) {
String json = "" ;
try {
InputStream stream = oConvertUtils. class . getClassLoader ( ) . getResourceAsStream ( url. replace ( "classpath:" , "" ) ) ;
json = IOUtils . toString ( stream, "UTF-8" ) ;
} catch ( IOException e) {
log. error ( e. getMessage ( ) , e) ;
}
return json;
}
}
1-10:SensitiveInfoUtil
package com. example. poi. desensitization. utils ;
import com. example. poi. desensitization. enums. SensitiveEnum ;
import com. example. poi. desensitization. annotation. SensitiveField ;
import com. example. poi. desensitization. utils. encryption. AesEncryptUtil ;
import lombok. extern. slf4j. Slf4j ;
import java. lang. reflect. Field ;
import java. lang. reflect. ParameterizedType ;
import java. util. Collections ;
import java. util. List ;
@Slf4j
public class SensitiveInfoUtil {
public static void handleNestedObject ( Object obj, Class entity, boolean isEncode) throws IllegalAccessException {
Field [ ] fields = obj. getClass ( ) . getDeclaredFields ( ) ;
for ( Field field : fields) {
if ( field. getType ( ) . isPrimitive ( ) ) {
continue ;
}
if ( field. getType ( ) . equals ( entity) ) {
field. setAccessible ( true ) ;
Object nestedObject = field. get ( obj) ;
handlerObject ( nestedObject, isEncode) ;
break ;
} else {
if ( field. getGenericType ( ) instanceof ParameterizedType ) {
ParameterizedType pt = ( ParameterizedType ) field. getGenericType ( ) ;
if ( pt. getRawType ( ) . equals ( List . class ) ) {
if ( pt. getActualTypeArguments ( ) [ 0 ] . equals ( entity) ) {
field. setAccessible ( true ) ;
Object nestedObject = field. get ( obj) ;
handleList ( nestedObject, entity, isEncode) ;
break ;
}
}
}
}
}
}
public static Object handlerObject ( Object obj, boolean isEncode) throws IllegalAccessException {
log. debug ( " obj --> " + obj. toString ( ) ) ;
long startTime= System . currentTimeMillis ( ) ;
if ( oConvertUtils. isEmpty ( obj) ) {
return obj;
}
Field [ ] fields = obj. getClass ( ) . getDeclaredFields ( ) ;
for ( Field field : fields) {
boolean isSensitiveField = field. isAnnotationPresent ( SensitiveField . class ) ;
if ( isSensitiveField) {
if ( field. getType ( ) . isAssignableFrom ( String . class ) ) {
field. setAccessible ( true ) ;
String realValue = ( String ) field. get ( obj) ;
if ( realValue== null || "" . equals ( realValue) ) {
continue ;
}
SensitiveField sf = field. getAnnotation ( SensitiveField . class ) ;
if ( isEncode== true ) {
String value = SensitiveInfoUtil . getEncodeData ( realValue, sf. type ( ) ) ;
field. set ( obj, value) ;
} else {
if ( sf. type ( ) . equals ( SensitiveEnum . ENCODE ) ) {
String value = SensitiveInfoUtil . getDecodeData ( realValue) ;
field. set ( obj, value) ;
}
}
}
}
}
return obj;
}
public static void handleList ( Object obj, Class entity, boolean isEncode) {
List list = ( List ) obj;
if ( list. size ( ) > 0 ) {
Object first = list. get ( 0 ) ;
if ( first. getClass ( ) . equals ( entity) ) {
for ( int i= 0 ; i< list. size ( ) ; i++ ) {
Object temp = list. get ( i) ;
try {
handlerObject ( temp, isEncode) ;
} catch ( IllegalAccessException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
public static String getDecodeData ( String data) {
String result = null ;
try {
result = AesEncryptUtil . desEncrypt ( data) ;
} catch ( Exception exception) {
log. debug ( "数据解密错误,原数据:" + data) ;
}
if ( oConvertUtils. isEmpty ( result) && oConvertUtils. isNotEmpty ( data) ) {
result = data;
}
return result;
}
public static String getEncodeData ( String data, SensitiveEnum sensitiveEnum) {
String result;
switch ( sensitiveEnum) {
case ENCODE :
try {
result = AesEncryptUtil . encrypt ( data) ;
} catch ( Exception exception) {
log. error ( "数据加密错误" , exception. getMessage ( ) ) ;
result = data;
}
break ;
case CHINESE_NAME :
result = chineseName ( data) ;
break ;
case ID_CARD :
result = idCardNum ( data) ;
break ;
case FIXED_PHONE :
result = fixedPhone ( data) ;
break ;
case MOBILE_PHONE :
result = mobilePhone ( data) ;
break ;
case ADDRESS :
result = address ( data, 3 ) ;
break ;
case EMAIL :
result = email ( data) ;
break ;
case BANK_CARD :
result = bankCard ( data) ;
break ;
case CNAPS_CODE :
result = cnapsCode ( data) ;
break ;
default :
result = data;
}
return result;
}
private static String chineseName ( String fullName) {
if ( oConvertUtils. isEmpty ( fullName) ) {
return "" ;
}
return formatRight ( fullName, 1 ) ;
}
private static String chineseName ( String familyName, String firstName) {
if ( oConvertUtils. isEmpty ( familyName) || oConvertUtils. isEmpty ( firstName) ) {
return "" ;
}
return chineseName ( familyName + firstName) ;
}
private static String idCardNum ( String id) {
if ( oConvertUtils. isEmpty ( id) ) {
return "" ;
}
return formatLeft ( id, 4 ) ;
}
private static String fixedPhone ( String num) {
if ( oConvertUtils. isEmpty ( num) ) {
return "" ;
}
return formatLeft ( num, 4 ) ;
}
private static String mobilePhone ( String num) {
if ( oConvertUtils. isEmpty ( num) ) {
return "" ;
}
int len = num. length ( ) ;
if ( len< 11 ) {
return num;
}
return formatBetween ( num, 3 , 4 ) ;
}
private static String address ( String address, int sensitiveSize) {
if ( oConvertUtils. isEmpty ( address) ) {
return "" ;
}
int len = address. length ( ) ;
if ( len< sensitiveSize) {
return address;
}
return formatRight ( address, sensitiveSize) ;
}
private static String email ( String email) {
if ( oConvertUtils. isEmpty ( email) ) {
return "" ;
}
int index = email. indexOf ( "@" ) ;
if ( index <= 1 ) {
return email;
}
String begin = email. substring ( 0 , 1 ) ;
String end = email. substring ( index) ;
String stars = "**" ;
return begin + stars + end;
}
private static String bankCard ( String cardNum) {
if ( oConvertUtils. isEmpty ( cardNum) ) {
return "" ;
}
return formatBetween ( cardNum, 6 , 4 ) ;
}
private static String cnapsCode ( String code) {
if ( oConvertUtils. isEmpty ( code) ) {
return "" ;
}
return formatRight ( code, 2 ) ;
}
private static String formatRight ( String str, int reservedLength) {
String name = str. substring ( 0 , reservedLength) ;
String stars = String . join ( "" , Collections . nCopies ( str. length ( ) - reservedLength, "*" ) ) ;
return name + stars;
}
private static String formatLeft ( String str, int reservedLength) {
int len = str. length ( ) ;
String show = str. substring ( len- reservedLength) ;
String stars = String . join ( "" , Collections . nCopies ( len- reservedLength, "*" ) ) ;
return stars + show;
}
private static String formatBetween ( String str, int beginLen, int endLen) {
int len = str. length ( ) ;
String begin = str. substring ( 0 , beginLen) ;
String end = str. substring ( len- endLen) ;
String stars = String . join ( "" , Collections . nCopies ( len- beginLen- endLen, "*" ) ) ;
return begin + stars + end;
}
}
1-11:SymbolConstant
package com. example. poi. desensitization. utils ;
public class SymbolConstant {
public static final String SPOT = "." ;
public static final String DOUBLE_BACKSLASH = "\\" ;
public static final String COLON = ":" ;
public static final String COMMA = "," ;
public static final String LEFT_CURLY_BRACKET = "{" ;
public static final String RIGHT_CURLY_BRACKET = "}" ;
public static final String WELL_NUMBER = "#" ;
public static final String SINGLE_SLASH = "/" ;
public static final String DOUBLE_SLASH = "//" ;
public static final String EXCLAMATORY_MARK = "!" ;
public static final String UNDERLINE = "_" ;
public static final String SINGLE_QUOTATION_MARK = "'" ;
public static final String ASTERISK = "*" ;
public static final String PERCENT_SIGN = "%" ;
public static final String DOLLAR = "$" ;
public static final String AND = "&" ;
public static final String SPOT_SINGLE_SLASH = "../" ;
public static final String SPOT_DOUBLE_BACKSLASH = "..\\" ;
public static final String SYS_VAR_PREFIX = "#{" ;
public static final String DOUBLE_LEFT_CURLY_BRACKET = "{{" ;
public static final String SQUARE_BRACKETS_LEFT = "[" ;
public static final String SQUARE_BRACKETS_RIGHT = "]" ;
}
2:必须导入的POM的依赖
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-aspects</ artifactId>
< version> 5.2.6.RELEASE</ version>
</ dependency>
< dependency>
< groupId> commons-io</ groupId>
< artifactId> commons-io</ artifactId>
< version> 2.6</ version>
</ dependency>
< dependency>
< groupId> cn.hutool</ groupId>
< artifactId> hutool-all</ artifactId>
< version> 5.7.10</ version>
</ dependency>