Package com.lgx8.right.common

Source Code of com.lgx8.right.common.StrTool

package com.lgx8.right.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.StringTokenizer;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StrTool {

    public static boolean DEBUG_MODE = true;

    public StrTool() {
        super();
    }

    public static int keyWordCount(String src, String key) {
        StringTokenizer st = new StringTokenizer(src, key);
        int count = 0;
        while (st.hasMoreTokens()) {
            st.nextToken();
            count++;
        }
        return count;
    }

//    public static String getStrFromSet(Set set) {
//        Iterator it = set.iterator();
//        String content = "";
//        while (it.hasNext()) {
//            BaseBusinessOBJ bo = (BaseBusinessOBJ) it.next();
//            content += bo.getName() + ",";
//
//        }
//        if (content.equals(""))
//            return "";
//        content = content.substring(0, content.length() - 1);
//        return content;
//    }

    /**
     * byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示,
     * 因为java中的byte的toString无法实现这一点,我们又没有C语言中的 sprintf(outbuf,"%02X",ib)
     *
     * @param ib
     * @return
     */
    public static String byte2HEX(byte ib) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
                'b', 'c', 'd', 'e', 'f' };
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0F];
        ob[1] = Digit[ib & 0X0F];
        String s = new String(ob);
        return s;
    }

    /**
     * 将传入的字符串进行MD5加密
     *
     * @param source
     * @return
     */
    public static String toMD5(String source) {
        // 加密后的字符串
        String newstr = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(source.getBytes());
            for (int i = 0; i < bs.length; i++) {
                newstr += byte2HEX(bs[i]);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return newstr;
    }

    static final byte[] keyBytes = { 0x11, 0x22, 0x4F, 0x58, 0x10, 0x40, 0x38,
            0x28, 0x25, 0x79, 0x51, 0x55, 0x66, 0x77, 0x29, 0x74, 0x30, 0x40,
            0x36, 0x28 };

    public static SecretKey get3DesKey(String key) {
        if (key == null) {
            key = "private key";
        }

        // 生成一个 DESede 密钥对象
        SecretKey theKey = null;

        try {
            byte[] encryptKey = new byte[25];
            byte[] tempKey = key.getBytes();

            if (tempKey.length < 24 && tempKey.length > 0) {
                int times = 24 / tempKey.length + 1;
                encryptKey = new byte[tempKey.length * times];
            }
            for (int i = 0, j = 0; i < encryptKey.length; i++, j++) {
                encryptKey[i] = tempKey[j];
                if (j == tempKey.length - 1) {
                    j = -1;
                }
            }

            // 为上一密钥创建一个指定的 DESSede key
            DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
            // 得到 DESSede keys
            SecretKeyFactory keyFactory = SecretKeyFactory
                    .getInstance("DESede");
            theKey = keyFactory.generateSecret(spec);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return theKey;
    }

    /**
     * 用指定的key 加密指定的字符串
     *
     * @param strPwd
     * @param strKey
     * @return
     * @throws InvalidKeySpecException
     */
    public static String getEncryptStr(String strPwd, String strKey) {
        if (strPwd == null || "".equals(strPwd)) {
            return "";
        }
        // 获取加密key
        SecretKey theKey = get3DesKey(strKey);
        byte[] ciphertext = null;
        String cipherString = "";

        try {
            Cipher cipher = Cipher.getInstance("Desede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, theKey);
            // 注意把字符串转换成字节需要指定编码方式,一般用此“UTF8”。
            byte[] plaintext = strPwd.getBytes("UTF8");
            ciphertext = cipher.doFinal(plaintext);

            BASE64Encoder enc = new BASE64Encoder();
            cipherString = enc.encode(ciphertext);
        } catch (Exception e) {
            cipherString = strPwd;
            System.err.println("加密方法StrTool.getEncryptStr()异常(Key值存在问题):\n"
                    + e.getMessage());
        }
        return cipherString;
    }

    /**
     * 用指定的key 解密指定的字符串
     *
     * @param strPwdCode
     * @param strKey
     * @return
     * @throws InvalidKeyException
     */
    public static String getDencryptedStr(String strPwdCode, String strKey) {
        if (strPwdCode == null || "".equals(strPwdCode)) {
            return "";
        }
        // 获取解密key
        SecretKey theKey = get3DesKey(strKey);

        String output = "";
        try {
            Cipher cipher = Cipher.getInstance("Desede/ECB/PKCS5Padding");
            BASE64Decoder dec = new BASE64Decoder();
            byte[] ciphertext = dec.decodeBuffer(strPwdCode);
            // 解密过程。
            cipher.init(Cipher.DECRYPT_MODE, theKey);
            byte[] decryptedText = cipher.doFinal(ciphertext);
            output = new String(decryptedText, "UTF8");
        } catch (Exception e) {
            output = strPwdCode;
            System.err
                    .println("解密方法StrTool.getDencryptedStr()异常(Key值存在问题或字符串未加密过):\n"
                            + e.getMessage());
        }
        return output;
    }
    /**
     * 把ip地址转换为字符串
     * @param ip  ip地址
     * @return  字符串
     * modify by lvwei 2009/11/18
     */
    public static long ipStr2Long(String ip) {
        String[] ips = ip.split("\\.");    
        return ((StrTool.parseLong(ips[0]) <<24)
                 + (StrTool.parseLong(ips[1]) <<16)
                 + (StrTool.parseLong(ips[2]) <<8)
                 + StrTool.parseLong(ips[3]));
       
    }

    public static String ipLong2Str(long ip) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            long temp = ip & 0xff;
            sb.insert(0, temp);
            if (i != 3)
                sb.insert(0, ".");
            ip = ip >> 8;
        }
        return sb.toString();
    }

    public static void printStr(String msg) {
        if (DEBUG_MODE) {
            System.out.print(msg + "\n");
        }
    }

    public static void printException(Exception exc) {
        if (DEBUG_MODE) {
            if (exc != null) {
                exc.printStackTrace();
            }
        }
    }

    public static int parseInt(String str) {
        if (str != null && !"".equals(str)) {
            try {
                return Integer.parseInt(str);
            } catch (Exception ex) {
                printException(ex);
            }
        }
        return 0;
    }

    public static int parseInt(String str, int val) {
        if (str != null && !"".equals(str)) {
            try {
                return Integer.parseInt(str, val);
            } catch (Exception ex) {
                printException(ex);
            }
        }
        return 0;
    }

    public static long parseLong(String str) {
        if (str != null && !"".equals(str)) {
            try {
                return Long.parseLong(str);
            } catch (Exception ex) {
                printException(ex);
            }
        }
        return 0;
    }

    public static double parseDouble(String str) {
        if (str != null && !"".equals(str)) {
            try {
                return Double.parseDouble(str);
            } catch (Exception ex) {
                printException(ex);
            }
        }
        return 0.0;
    }

    public static boolean isNum(String str) {
        boolean flag = true;
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (!Character.isDigit(ch[i])) {
                flag = false;
                break;
            }
        }
        return flag;
    }
   
    //===== Begin ========JavaScript escape/unescape 编码的 Java 实现=====================
    private final static String[] hex = { "00", "01", "02", "03", "04", "05",
            "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10",
            "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B",
            "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26",
            "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31",
            "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C",
            "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47",
            "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52",
            "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D",
            "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68",
            "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73",
            "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E",
            "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
            "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94",
            "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
            "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA",
            "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5",
            "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0",
            "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB",
            "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6",
            "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1",
            "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC",
            "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7",
            "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" };

    private final static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01,
            0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
            0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F };

    public static String unescape(String s) {
        StringBuffer sbuf = new StringBuffer();
        int i = 0;
        int len = s.length();
        while (i < len) {
            int ch = s.charAt(i);
            if ('A' <= ch && ch <= 'Z') {
                sbuf.append((char) ch);
            } else if ('a' <= ch && ch <= 'z') {
                sbuf.append((char) ch);
            } else if ('0' <= ch && ch <= '9') {
                sbuf.append((char) ch);
            } else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
                    || ch == '~' || ch == '*' || ch == '\'' || ch == '('
                    || ch == ')') {
                sbuf.append((char) ch);
            } else if (ch == '%') {
                int cint = 0;
                if ('u' != s.charAt(i + 1)) {
                    cint = (cint << 4) | val[s.charAt(i + 1)];
                    cint = (cint << 4) | val[s.charAt(i + 2)];
                    i += 2;
                } else {
                    cint = (cint << 4) | val[s.charAt(i + 2)];
                    cint = (cint << 4) | val[s.charAt(i + 3)];
                    cint = (cint << 4) | val[s.charAt(i + 4)];
                    cint = (cint << 4) | val[s.charAt(i + 5)];
                    i += 5;
                }
                sbuf.append((char) cint);
            } else {
                sbuf.append((char) ch);
            }
            i++;
        }
        return sbuf.toString();
    }

    public static String escape(String s) {
        StringBuffer sbuf = new StringBuffer();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            int ch = s.charAt(i);
            if (ch == ' ') { // space : map to '+'
                sbuf.append('+');
            } else if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was
                sbuf.append((char) ch);
            } else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was
                sbuf.append((char) ch);
            } else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was
                sbuf.append((char) ch);
            } else if (ch == '-'
                    || ch == '_' // unreserved : as it was
                    || ch == '.' || ch == '!' || ch == '~' || ch == '*'
                    || ch == '\'' || ch == '(' || ch == ')') {
                sbuf.append((char) ch);
            } else if (ch <= 0x007F) { // other ASCII : map to %XX
                sbuf.append('%');
                sbuf.append(hex[ch]);
            } else { // unicode : map to %uXXXX
                sbuf.append('%');
                sbuf.append('u');
                sbuf.append(hex[(ch >>> 8)]);
                sbuf.append(hex[(0x00FF & ch)]);
            }
        }
        return sbuf.toString();
    }

    //===== End ========JavaScript escape/unescape 编码的 Java 实现=====================
    /**
     * 如果是null转化为空串,否则返回原字符串
     * create by yangwm in Nov 4, 2008 9:15:00 PM
     * @param str
     * @return
     */
    public static final String nullToEmptyString(String str) {
        return str == null ? "" : str;
    }
   
    /**
     * 如果是null(包括"null")转化为空串,否则返回原字符串
     * create by yangwm in Nov 4, 2008 9:15:00 PM
     * @param str
     * @return
     */
    public static final String nullStringToEmptyString(String str) {
        return str == null || "null".equalsIgnoreCase(str) ? "" : str;
    }
   
    /**
     * 比较两个字符串是否相同,如果两个字符串为null或""均视为相同
     * create by yangwm in Nov 4, 2008 8:52:57 PM
     * @param str1
     * @param str2
     * @return 相同为true,否则false
     */
    public static boolean equals(String str1, String str2) {
        str1 = nullToEmptyString(str1);
        str2 = nullToEmptyString(str2);
        return str1.equals(str2);
    }
   
    /**
     * 比较两个字符串是否相同,如果两个字符串为null或""均视为相同且忽略大小写
     * create by yangwm in Nov 4, 2008 8:52:57 PM
     * @param str1
     * @param str2
     * @return 相同为true,否则false
     */
    public static boolean equalsIgnoreCase(String str1, String str2) {
        str1 = nullToEmptyString(str1);
        str2 = nullToEmptyString(str2);
        return str1.equalsIgnoreCase(str2);
    }
   
    /**
     * 比较两个字符串是否相同,如果两个字符串为null或""或"null"均视为相同
     * create by yangwm in Nov 4, 2008 8:52:57 PM
     * @param str1
     * @param str2
     * @return 相同为true,否则false
     */
    public static boolean equateNullIgnoreCase(String str1, String str2) {
        str1 = nullStringToEmptyString(str1);
        str2 = nullStringToEmptyString(str2);
        return str1.equals(str2);
    }
   
    /**
     * 字符串是否为空, null或""均视为空
     * @param value
     * @return
     */
    public static boolean isNullStr(String value) {
        return value == null || value.trim().equals("");
    }
   
    /**
     * 字符串是否为空, null或""或"null"均视为空
     * create by yangwm in Nov 5, 2008 3:59:24 PM
     * @param value
     * @return
     */
    public static boolean isEquateNullStr(String value) {
        return equateNullIgnoreCase(null, value);
    }


    // ---------------------- main test ---------------------------
    public static void main(String[] args) {
        // String str = "bid=a,bid=b,bid=c";
        // System.out.println(keyWordCount(str, ","));
        String stest = "1234 abcd[]()<+>,.~\\";
        System.out.println(stest);

        System.out.println(toMD5("abc123"));
       

        // test nullToEmptyString and test nullStringToEmptyString
        System.out.println("------------test nullToEmptyString and nullStringToEmptyString ------------");
        System.out.println(nullToEmptyString(null));
        System.out.println(nullToEmptyString(""));
        System.out.println(nullToEmptyString("null"));
        System.out.println(nullStringToEmptyString(null));
        System.out.println(nullStringToEmptyString(""));
        System.out.println(nullStringToEmptyString("null"));
       
        // test equate
//        System.out.println("------------test equate and equalsIgnoreCase ------------");
//        System.out.println(equate(null, null));
//        System.out.println(equate("", ""));
//        System.out.println(equate(null, ""));
//        System.out.println(equate("", null));
//        System.out.println(equate(null, "abc"));
//        System.out.println(equate("abc", "ABC"));
//        System.out.println(equateIgnoreCase("abc", "ABC"));
       
    }

}
TOP

Related Classes of com.lgx8.right.common.StrTool

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.