chenjiahe
2022-01-13 c64e1248bfda3ac8c5120e529fd096dfc4846629
src/main/java/com/hx/util/mysql/aes/MysqlHexAes.java
@@ -6,6 +6,7 @@
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;
/**
 * mybatis数据库的AES_ENCRYPT(加密)和AES_DECRYPT(解密)
@@ -37,6 +38,9 @@
     */
    public static String decryptData(String data,String aesKey,String encoding) {
        try{
            if(data == null){
                return null;
            }
            if(StringUtils.isEmpty(encoding)){
                encoding = "UTF-8";
            }
@@ -45,7 +49,7 @@
            decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(aesKey, encoding));
            data = new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray())));
        }catch (Exception e){
            throw new RuntimeException("解密失败:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return data;
    }
@@ -58,6 +62,9 @@
     */
    public static String encryptData(String data,String aesKey,String encoding) {
        try {
            if(data == null){
                return null;
            }
            if (StringUtils.isEmpty(encoding)) {
                encoding = "UTF-8";
            }
@@ -71,9 +78,24 @@
            }
            data = builder.toString().toUpperCase();
        } catch (Exception e) {
            throw new RuntimeException("加密失败:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return data;
    }
    /**
     * 判断是不是十六进制的字符串(字母是大写的)
     * @param str 需要判断的字符串
     * @return true or false
     */
    public static boolean isHexStrValid(String str) {
        if(str == null){
            return false;
        }
        String pattern = "^[0-9A-F]+$";
        return Pattern.compile(pattern).matcher(str).matches();
    }
}