自定义@AES注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AES {
}
给需要进行AES加解密的字段添加该注解
@ApiModelProperty(value = "委托客户联系电话")
@TableField("CUST_PHONE")
@AES
private String custPhone;
解析实体类字段注解 进行加密或解密操作
/**
* 处理AES注解字段
* @param entity
* @param type true加密 false解密
* @return
* @param <T>
*/
public static <T> T handleFields(T entity,boolean type){
try {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(AES.class)) {
field.setAccessible(true);
String tableValue = (String) field.get(entity);
if (StringUtils.isNotEmpty(tableValue)) {
String newValue = type ? encrypt(tableValue, "") : decrypt(tableValue, "");
field.set(entity, newValue);
}
}
}
} catch (IllegalAccessException e) {
LOG.info("处理AES注解字段异常",e.toString());
}
return entity;
}
加密方法
/**
* 加密
* @param ssrc
* @param skey 可为空
* @return
*/
public static String encrypt(String ssrc, String skey){
try {
skey = StringUtils.isEmpty(skey) ? key : skey;
if (skey.length() != 16) {
LOG.info("Key长度不是16位");
return null;
} else {
byte[] raw = skey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(ssrc.getBytes(StandardCharsets.UTF_8));
return (new Base64()).encodeToString(encrypted);
}
} catch (Exception e) {
LOG.info(e.toString());
return null;
}
}
解密方法
/**
* 解密
* @param ssrc
* @param skey 可为空
* @return
*/
public static String decrypt(String ssrc, String skey){
try {
skey = StringUtils.isEmpty(skey) ? key : skey;
if (skey.length() != 16) {
LOG.info("Key长度不是16位");
return null;
} else {
byte[] raw = skey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = (new Base64()).decode(ssrc);
byte[] original = cipher.doFinal(decrypted);
String originalString = new String(original, StandardCharsets.UTF_8);
return originalString;
}
} catch (Exception e) {
LOG.info(e.toString());
return null;
}
}