sqlUtils.java

import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.proxy.jdbc.ClobProxyImpl;
import com.resafety.core.env.DBEnvironment;
import com.resafety.core.env.PlatformEnvironment;

import oracle.sql.CLOB;

import org.apache.commons.codec.binary.Base64;

public class Util {
    // 加密key和盐
    private static String KEY = "dufy20170329java";
    private static String IV = "dufy20170329java";

    // 获取当前数据库类型
    public static String oraOrMssql() {
        DBEnvironment dBEnvironment = new DBEnvironment();
        String dbtype = dBEnvironment.getType();
        String checkDbType = "ORA";
        switch (dbtype) { 
        case "oracle":
            checkDbType = "ORA";
            break;
        case "mysql":
            checkDbType = "MYSQL";
            break;    
        case "sqlserver":
            checkDbType = "MSSQL";
            break;    
        case "GAUSSDB":
            checkDbType = "GAUSSDB";
            break;    
        }
        
        return checkDbType;
    }

    // clob字段druidBUG处理
    public static String oracleClobToString(ClobProxyImpl cp) {
        oracle.sql.CLOB clob = (CLOB) cp.getRawClob();
        try {
            return (clob == null ? null : clob.getSubString(1, (int) clob.length()));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getRandom() {
        int max = 100;
        int min = 1;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }

    public static void main(String[] args) {
        System.out.println(getRandom());
    }

    /*@20190916
     *  检测字符串中是否包含可能引起sql注入的字符
     * 如果检测到包含危险的特殊字符,则返回false。如果不包含(验证通过),则返回true
     * */
    public static boolean checkAttack(String input) {
        input = input.trim();
        if (input == null || input.equals(""))
            return false;
        // 检测sql
        String reg = "../:sleep:bin:readdirSync:Shellshock:AVAK$:WF'SQL:{ A;}>A[$($())]:http://:echo:and:exec:insert:select:delete:update:count:*:%:chr:mid:master:truncate:declare:../:HTTP/:AVAK$:WF'SQL:or:+:having:1=1:eval:ltrim:||:--";
        // String reg =
        // "http:readdirSync:echo:exec:insert:delete:update:count:*:chr:mid:master:truncate:declare:HTTP/:AVAK$:WF'SQL:+:having:1=1:eval:ltrim:";
        String regs[] = reg.split(":");
        for (int i = 0; i < regs.length; i++) {
            if (input.indexOf(regs[i]) != -1) {
                // if(input.contains(regs[i])) {
                System.out.println("checkAttack: input String [" + input + "]" + "contains " + regs[i] + "!");

                return false;
                // }

            }
        }

        // System.out.println("checkAttack ["+ input+"] ok!" );
        return true;
    }

    /*
     * @20190917 专门用于检测数据库字段长度是否合法
     * 
     * @input:待检测字符串
     * 
     * @validlen:目标长度
     */
    public static boolean checkStrLen(String input, int validLen) {
        if (input == null || validLen <= 0)
            return false;
        if (input.length() > validLen)
            return false;

        return true;
    }

    /*
     * 检测一个字符串是否能够准确的转换成数值型数据,即,验证数值数据合法性
     */
    public static boolean checkStrToNum(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /*
     * 检测字符是否为整数(正)
     */
    public static boolean isPositiveInteger(String input) {// 正整数
        if (input == null || input.trim().equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile("^\\+{0,1}[1-9]\\d*");
        Matcher isNum = pattern.matcher(input);
        return isNum.matches();
    }

    /*
     * 检测字符是否为数字(包含正数、负数、小数)
     */
    public static Boolean checkValue(String str) {

        if (str.matches("^(\\-|\\+)?\\d+(\\.\\d+)?$")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean checkShellAttack(String input) {
        // 检测Shell
        String reg = "../:sleep:bin:readdirSync:Shellshock:AVAK$:WF'SQL:{ A;}>A[$($())]";
        String regs[] = reg.split(":");
        for (int i = 0; i < regs.length; i++) {
            if (input.indexOf(regs[i]) != -1) {
                System.out.println("checkAttack: input String [" + input + "]" + "contains " + regs[i] + "!");
                return false;
            }
        }
        return true;
    }

    public static String desEncrypt(String data) throws Exception {
        try {
            byte[] encrypted1 =  new Base64().decode(data.getBytes());
            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, "utf-8");
            return originalString;
            // return "a";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取request中所有的消息头
     * 
     * @param request
     * @return
     */
    public static Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
    //获取当前数据库连接名称
        public static String mysqlDBName(){
            DBEnvironment dBEnvironment = new DBEnvironment();
            String dbtype = dBEnvironment.getName();
            return dbtype;
        }
}

 

posted @ 2020-08-17 10:15  石shi  阅读(491)  评论(0编辑  收藏  举报