`

java 过滤HTML标签

    博客分类:
  • Java
阅读更多

Java如何过滤掉HTML标签呢?

java过滤html标记   java删除html标签

/**
	 * 删除input字符串中的html格式
	 * 
	 * @param input
	 * @param length
	 *            显示的字符的个数
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "").trim();
		str=SystemHWUtil.deleteAllCRLF(str);//delete all CRLF
		int len = str.length();
		if (length==SystemHWUtil.NEGATIVE_ONE|| len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	/**
	 * 返回纯文本,去掉html的所有标签,并且去掉空行
	 * 
	 * @param input
	 * @return
	 */
	public static String splitAndFilterString(String input) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		return SystemHWUtil.deleteCRLF(str);
	}

 应用:

		paperNews.setSplitAndFilterString(SystemHWUtil.splitAndFilterString(paperNews.getContent(), 120/*TODO */));
		
String content=paperNews.getContent();
			paperNews.setContent(SystemHWUtil.splitAndFilterString(content, DictionaryParam.getInt("news_settings", "content_max")));
			

 

 

1
3
分享到:
评论
3 楼 hw1287789687 2015-08-17  
mikzhang 写道
SystemHWUtil 的代码贴出来

package com.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;

import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;

import com.common.bean.PrivPubKeyBean;
import com.common.enu.SignatureAlgorithm;
import com.io.hw.exception.MyException;
import com.io.hw.file.util.FileUtils;
import com.string.widget.util.ValueWidget;
import com.time.util.TimeHWUtil;

/***
*
* @author huangwei
*
*/
public final class SystemHWUtil {
public static final String OSNAME = System.getProperty("os.name");
public static final String OSARCH = System.getProperty("os.arch");
public static final String SEPARATOR = System.getProperty("file.separator");
public static final String USER_DIR = System.getProperty("user.dir");
/***
* 操作系统临时目录:C:\Users\huangwei\AppData\Local\Temp\
*/
public static final String SYSTEM_TEMP_FOLDER = System
.getProperty("java.io.tmpdir");
/***
* 当前系统编码
*/
public static final String CURR_ENCODING = System
.getProperty("file.encoding");
public static final String LINE_SEPARATOR = System
.getProperty("line.separator");
public static final String CRLF = LINE_SEPARATOR; // Carriage Return/Line
// Feed
public static final String CRLF_LINUX = "\n";
public static final String CRLF_WINDOW = "\r\n";
public static final String CHARSET_UTF = "UTF-8";
/***
* 当前系统编码
*/
public static final String CHARSET_CURR = CURR_ENCODING;
public static final String CHARSET_GBK = "GBK";
public static final String CHARSET_GB2312 = "GB2312";
public static final String CHARSET_GB18030 = "GB18030";
public static final String CHARSET_UNICODE = "UNICODE";
public static final String CHARSET_ISO88591 = "ISO-8859-1";
public static final String[] CHARSET_ARRAY = new String[] { CHARSET_UTF,
CHARSET_GBK, CHARSET_GB2312 };

public static boolean isWindows = false;
public static boolean isHP_UX = false;
public static boolean isSolaris = false;
public static boolean isOS32bit = true;
public static final int BUFF_SIZE = 4096;
public static final int BUFF_SIZE_1024 = 1024;
public static final int SIZE_K=BUFF_SIZE_1024;
/***
* MB 的字节个数
*/
public static final int SIZE_M=BUFF_SIZE_1024*BUFF_SIZE_1024;
public static final String KEY_ALGORITHM_RSA = "RSA";
public final static String KEY_ALGORITHM_DES = "DES";
public static final String KEY_ALGORITHM_SHA1withRSA = "SHA1withRSA";
public static final String KEY_SHA = "SHA";
public static final String KEY_SHA1 = "SHA-1";
public static final String KEY_MD5 = "MD5";
public static final String KEY_HMAC_SHA256 = "HMACSHA256";
public static final String KEY_HMAC_SHA1 = "HmacSHA1";
public static final String CERTIFICATEFACTORY_X509 = "X.509";
public static final char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static BigInteger BIGINT1 = BigInteger.valueOf(1l);
public static final String CONTENTTYPE_HTML = "text/html";
public static final String CONTENTTYPE_JSON = "application/json";
public static final String CONTENTTYPE_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";

public static final String CONTENTTYPE_OCTET_STREAM = "application/octet-stream";
/***
* 应答(response)中的Content-Type:网页
*/
public static final String RESPONSE_CONTENTTYPE_HTML="text/html";
/**
* 应答(response)中的Content-Type:普通文本
*/
public static final String RESPONSE_CONTENTTYPE_PLAIN="text/plain";
/***
* 应答(response)中的Content-Type:json,UTF-8编码
*/
public static final String RESPONSE_CONTENTTYPE_JSON_UTF="application/json;charset=UTF-8";
/***
* 应答(response)中的Content-Type:json,GBK编码
*/
public static final String RESPONSE_CONTENTTYPE_JSON_GBK="application/json;charset=GBK";
/***
* 应答(response)中的Content-Type:二进制文件,例如
*/
public static final String RESPONSE_CONTENTTYPE_BINARY="application/octet-stream";
public static final String RESPONSE_CONTENTTYPE_JAVASCRIPT="application/javascript";
/***
* 兼容性比上面的更好
*/
public static final String RESPONSE_CONTENTTYPE_JAVASCRIPT2="text/javascript";
/***
* JPG图片
*/
public static final String RESPONSE_CONTENTTYPE_JPEG="image/jpeg";
/***
* png图片
*/
public static final String RESPONSE_CONTENTTYPE_PNG="image/png";
public static final String RESPONSE_CONTENTTYPE_SWF="application/x-shockwave-flash";
public static final String PROCOTOL_HTTP = "http";
public static final String PROCOTOL_HTTPS = "https";
public static final String COLON = ":";
/**
* 字符串空格
*/
public static final String BLANK = " ";
/***
* 英文句点
*/
public static final String ENGLISH_PERIOD = ".";
/***
* 英文双引号
*/
public static final String ENGLISH_QUOTES = "\"";
/***
* "0"
*/
public static final String ZERO_STRING = "0";
public static final String DIVIDING_LINE = "---------------------------------------";
/***
* -1
*/
public static final int NEGATIVE_ONE = -1;
/***
* 空字符串:""
*/
public static final String EMPTY = "";
/***
* 逗号
*/
public static final String ENGLISH_COMMA = ",";
public static final String SWING_DIALOG_RED = "<font color=\"red\"  style=\"font-weight:bold;\">%s</font>";
public static final String SWING_DIALOG_BLUE = "<font color=\"blue\"  style=\"font-weight:bold;\">%s</font>";
public static final String BR_HTML = "<br />";
public static final String LABEL_BROWSE = "浏览";
public static final String LABEL_PASTE = "粘贴";
public static final String LABEL_CLEANUP = "清空";
/***
* 下划线
*/
public static final String UNDERLINE = "_";
/***
* 中划线
*/
public static final String MIDDLE_LINE = "-";
/***
* 100
*/
public static final int NUMBER_100 = 100;
/***
* the ascci of blank space
*/
public static final byte BLANK_BYTE = (byte) 32;
public static final String  KEY_HEADER_COOLIE="Set-Cookie";
static {
if (SystemHWUtil.OSNAME.toLowerCase().contains("window")) {
isWindows = true;
}
if (SystemHWUtil.OSNAME.toLowerCase().contains("hp-ux")) {
isHP_UX = true;
}
if (SystemHWUtil.OSNAME.toLowerCase().contains("Solaris")) {
isSolaris = true;
}
if (SystemHWUtil.OSARCH.contains("64")) {
isOS32bit = false;
}
}

/***
* the unit of file size
*/
public static final String[] UNIT_SIZE = { "B", "KB", "MB", "GB", "TB",
"KTB" };
public static final String[] FILE_SIZE_ARR = UNIT_SIZE;
public static final String CMD_SHORT="cmd /c ";
private SystemHWUtil() {
throw new Error("Don't let anyone instantiate this class.");
}

public static void copyFile(String resourceFileName, String targetFileName)
throws IOException {
File resourceFile = new File(resourceFileName);
File targetFile = new File(targetFileName);
if (!resourceFile.exists()) {
System.out.println("[copyFile ]: resource file has not been found:"
+ resourceFileName);
}
if (!resourceFile.isFile()) {
System.out.println("[copyFile ]: directory can not be copyed:"
+ resourceFileName);
}

if (targetFile.isDirectory()) {
targetFile = new File(targetFile, resourceFile.getName());
}

FileInputStream resource = null;
FileOutputStream target = null;
try {
resource = new FileInputStream(resourceFile);
target = new FileOutputStream(targetFile);
copyFile(resourceFile, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resource != null) {
resource.close();
}
if (target != null) {
target.close();
}
}
}

/**
*
* @param srcFile
*            :must be regular file,can not be folder;
* @param targetFile
*            :must be regular file,can not be folder;
* @throws IOException
*/
public static void copyFile(File srcFile, File targetFile)
throws IOException {
FileInputStream in = new FileInputStream(srcFile);

FileOutputStream out = new FileOutputStream(targetFile);
copyFile(in, out);

}

public static void copyFile(InputStream in, FileOutputStream target)
throws IOException {
// File targetFile = new File(targetFileName);
// FileOutputStream target = null;
// if (targetFile.isDirectory())
// {
// targetFile = new File(targetFile, simpleName);
// }
try {
// target = new FileOutputStream(targetFile);
byte[] buffer = new byte[BUFF_SIZE];
int byteNum;

while ((byteNum = in.read(buffer)) != NEGATIVE_ONE) {
target.write(buffer, 0, byteNum);

}
System.out.println("[SystemUtil:copyFile]:file copy successfully!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
in = null;
}
if (target != null) {
target.close();
target = null;
}
}
}

/**
*
* @param fullpath
*            :/a/b/c/d
* @return /a/b/c/
*/
public static String getParentDir(File fullpath) {
// String parentDir = null;
if (ValueWidget.isNullOrEmpty(fullpath)) {
System.out.println("The first argument can not be null");
return null;
}

// if (fullpath.contains("/")) {
// int index=fullpath.lastIndexOf("/") ;
// parentDir = fullpath.substring(0, index+ 1);
// }
return fullpath.getParent();
}
/***
* 获取父目录
* @param fullpath
* @return
*/
public static String getParentDir(String fullpath) {
return getParentDir(new File(fullpath));
}
/***
* 若父目录不存在,即级联创建
* @param file
*/
public static File createParentFolder(File file){
String parentStr=file.getParent();
File parentFolder=new File(parentStr);
if(!parentFolder.exists()){
parentFolder.mkdirs();
}
return parentFolder;
}
/***
* 创建空文件,若文件已存在,则方法返回
* @param file
* @throws IOException
*/
public static void createEmptyFile(File file) throws IOException{
if(!file.exists()){//如果文件不存在
createParentFolder(file);
file.createNewFile();
}
}
/***
* 创建空文件,若文件已存在,则方法返回
* @param file
* @throws IOException
*/
public static void createEmptyFile(String file) throws IOException{
createEmptyFile(new File(file));
}
/***
* 若父目录不存在,即级联创建
* @param file
*/
public static void createParentFolder(String file){
createParentFolder(new File(file));
}

/**
*
* @param fullpath
*            :/a/b/c/d
* @return d
*/
public static String getFileSimpleName(String fullpath) {
// String parentDir = null;
if (null == fullpath) {
System.out.println("The first argument can not be null");
return null;
}
// if (fullpath.contains("/")) {
// parentDir = fullpath.substring(fullpath.lastIndexOf("/") + 1);
// }
return new File(fullpath).getName();
}

// public static void main(String[] args) throws IOException
// {
// copyFile("/home/whuang2/study/linux/study/c/main.exe", "/home/whuang2");
// }
public static String convertUTF2ISO(String oldName) {
if (oldName == null) {
return oldName;
}
try {
return new String(oldName.getBytes(CHARSET_UTF), CHARSET_ISO88591);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static String convertGBK2ISO(String input) {
if (input == null) {
return input;
}
try {
return new String(input.getBytes(CHARSET_GBK), CHARSET_ISO88591);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

/***
* convert GBK to UTF-8
*
* @param input
* @return
* @throws UnsupportedEncodingException
*/
public static byte[] convertGBK2UTF(byte[] input)
throws UnsupportedEncodingException {
return new String(input, SystemHWUtil.CHARSET_GBK)
.getBytes(SystemHWUtil.CHARSET_UTF);
}

/***
* convert from GBK to UTF-8
*
* @param input
* @return
*/
public static String convertGBK2UTF(String input) {
if (input == null) {
return input;
}
try {
return new String(input.getBytes(CHARSET_GBK), CHARSET_UTF);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static byte[] convertFromeGBK(byte[] input, String toCharset)
throws UnsupportedEncodingException {
return new String(input, SystemHWUtil.CHARSET_GBK).getBytes(toCharset);
}

/***
* convert utf-8 to gbk
*
* @param input
* @return
*/
public static String convertUTF2GBK(String input) {
if (input == null) {
return input;
}
try {
return new String(input.getBytes(CHARSET_UTF), CHARSET_GBK);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static String convertISO2Specified(String oldName, String newEncoding) {
if (oldName == null) {
return oldName;
}
try {
return new String(oldName.getBytes(CHARSET_ISO88591), newEncoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static String convertISO2GBK(String input) {
return convertISO2Specified(input, CHARSET_GBK);
}

public static String convertISO2UTF(String oldName) {
return convertISO2Specified(oldName, CHARSET_UTF);
}

public static void printFilesSimpleName(File[] files) {
for (File file : files) {
System.out.println(file.getName());
}
}

public static void printFilesFilePath(File[] files) {
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}

public static void printFilesFilePath(List<File> files) {
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}

/***
*
* @param srcfile
*            : source file
* @param targfile
*            : target file
* @param inputCharset
*            : from charset
* @param outputCharset
*            : to charset
*/
public static void convertEncoding(File srcfile, File targfile,
String inputCharset, String outputCharset) {
FileInputStream fin = null;
FileOutputStream fout = null;
char[] cbuf = new char[BUFF_SIZE];
int size_char;
try {
fin = new FileInputStream(srcfile);
fout = new FileOutputStream(targfile);
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
isr = new InputStreamReader(fin, inputCharset);
osw = new OutputStreamWriter(fout, outputCharset);
while ((size_char = isr.read(cbuf)) != NEGATIVE_ONE) {
osw.write(cbuf, 0, size_char);
}
//
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
isr.close();
osw.close();
} catch (IOException e1) {
e1.printStackTrace();
}

}

} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
try {
if (fin != null) {
fin.close();
}
if (fout != null) {
fout.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

public static byte[] convertEncoding(byte[] oldContent, String oldCharset,
String newCharset) {
if (ValueWidget.isNullOrEmpty(oldContent)
|| ValueWidget.isNullOrEmpty(oldCharset)
|| ValueWidget.isNullOrEmpty(newCharset)) {
return null;
}
try {
return new String(oldContent,oldCharset).getBytes(newCharset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

/**
* delete the same one
*
* @param list
* @return
*/
public static List<String> guolv(List<String> list) {
List<String> newlist = new ArrayList<String>();
if (list != null && list.size() > 0) {
newlist.add(list.get(0));
for (int i = 1; i < list.size(); i++) {
if (!newlist.contains(list.get(i))) {
newlist.add(list.get(i));
}
}
}
return newlist;
}

/***
* test ok!<br> 去重
* @param strs
* @return
*/
public static String[] guolv(String[]strs){
List<String>list =new ArrayList<String>();
list.add(strs[0]);//数组的第一个元素
for(int i=1;i<strs.length;i++){
String  string=strs[i];
if(!isContains(list, string)){
list.add(string);
}
}
return list2Arr(list);
}
/***
* delete CRLF; delete empty line ;delete blank lines
*
* @param input
* @return
*/
private static String deleteCRLFOnce(String input) {
if (ValueWidget.isHasValue(input)) {
return input.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1")
.replaceAll("^((\r\n)|\n)", "");
} else {
return null;
}
}

/***
* Delete all spaces
*
* @param input
* @return
*/
public static String deleteAllCRLF(String input) {
return input.replaceAll("((\r\n)|\n)[\\s\t ]*", "").replaceAll(
"^((\r\n)|\n)", "");
}

public static String CRLF2Blank(String input) {
return input.replaceAll("((\r\n)|\n)[\\s\t ]*", " ").replaceAll(
"^((\r\n)|\n)", " ").replaceAll("[ ]{2,}", " ");//注意:replace不支持正则表达式
}
/**
* delete CRLF; delete empty line ;delete blank lines
*
* @param input
* @return
*/
public static String deleteCRLF(String input) {
input = SystemHWUtil.deleteCRLFOnce(input);
return SystemHWUtil.deleteCRLFOnce(input);
}

/***
* Use uniqueness of collection
*
* @param list
* @return
*/
public static List<String> guolv2(List<String> list) {
Set<String> set = new HashSet<String>(list);
return new ArrayList<String>(set);
}

/**
* delete the same one
*
* @param list
* @return
*/
public static List<Integer> guolvInteger(List<Integer> list) {
List<Integer> newlist = new ArrayList<Integer>();
if (list != null && list.size() > 0) {
newlist.add(list.get(0));
for (int i = 1; i < list.size(); i++) {
if (!newlist.contains(list.get(i))) {
newlist.add(list.get(i));
}
}
}
return newlist;
}

public static List<Integer> guolvInteger2(List<Integer> list) {
Set<Integer> set = new HashSet<Integer>(list);
return new ArrayList<Integer>(set);
}

/**
* 字节数大于1,则返回true
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
return String.valueOf(c).getBytes().length > 1;
}

/**
* 判断str 中的所有字符是否全部是中文字符(包括中文的标点符号)
*
* @param str
* @return
*/
public static boolean isAllChinese(String str) {
char[] cs = null;
if (str.length() == 1) {
cs = new char[1];
cs[0] = str.charAt(0);
} else {
cs = str.toCharArray();
}
for (int i = 0; i < cs.length; i++) {
char c = cs[i];
if (!isChinese(c)) {
return false;
}
}
return true;
}

public static boolean isHasChinses(String str) {
String encodeName = "UTF-8";
for (int i = 0; i < str.length(); i++) {
try {
String singleStr = str.substring(i, i + 1);
int leng = getEncodeLength(singleStr, encodeName);
// System.out.println(singleStr + "\t" + leng);
if (leng == 9)// 表示是中文字符
{
// System.out.println("有中文");
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}

public static boolean isHasChinses2(String str) {
String encodeName = "UTF-8";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
try {
char c = chars[i];
int leng = getEncodeLength(c, encodeName);
// System.out.println(singleStr + "\t" + leng);
if (leng == 9)// 表示是中文字符
{
// System.out.println("有中文");
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
return false;
}

public static int getEncodeLength(String str, String encodeName)
throws Exception, UnsupportedEncodingException {// 返回值为9 的话,则说明有中文。
if (str.length() != 1) {
throw new Exception("超过一个字符");
}
String encod = URLEncoder.encode(str, "UTF-8");
return encod.length();
}

public static int getEncodeLength(char c, String encodeName)
throws MyException, UnsupportedEncodingException {// 返回值为9
// 的话,则说明有中文。
String encod = URLEncoder.encode(String.valueOf(c), "UTF-8");
return encod.length();
}

/**
* 删除input字符串中的html格式
*
* @param input
* @param length
*            显示的字符的个数
* @return
*/
public static String splitAndFilterString(String input, int length) {
if (input == null || input.trim().equals("")) {
return "";
}
// 去掉所有html元素,
String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
"<[^>]*>", "");
str = str.replaceAll("[(/>)<]", "").trim();
str=SystemHWUtil.deleteAllCRLF(str);//delete all CRLF
int len = str.length();
if (length==SystemHWUtil.NEGATIVE_ONE|| len <= length) {
return str;
} else {
str = str.substring(0, length);
str += "......";
}
return str;
}

/**
* 返回纯文本,去掉html的所有标签,并且去掉空行
*
* @param input
* @return
*/
public static String splitAndFilterString(String input) {
if (input == null || input.trim().equals("")) {
return "";
}
// 去掉所有html元素,
String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
"<[^>]*>", "");
str = str.replaceAll("[(/>)<]", "");
return SystemHWUtil.deleteCRLF(str);
}

public static boolean contains(List<Object> list, Object value) {
if (list == null || list.size() == 0) {
return false;
} else {
for (int i = 0; i < list.size(); i++) {
String valueStr;
if (value instanceof File) {
valueStr = ((File) value).getName();
} else {
valueStr = value.toString();
}
Object obj = list.get(i);
if (obj instanceof File) {
if (list.contains(valueStr)
|| ((File) obj).getName().toString()
.equals(valueStr)) {
return true;
}
} else {
if (list.contains(valueStr)
|| list.get(i).toString().equals(valueStr)) {
return true;
}
}
}
}
return false;
}

/**
* minus Set
*
* @param oldList
* @param list
* @return
*/
public static List<Object> getMinusSet(List oldList, List list) {
List selectedList = null;
if (oldList != null) {
selectedList = new ArrayList<Object>();
int leng = oldList.size();
if (leng != 0) {
for (int i = 0; i < leng; i++) {
Object obj = oldList.get(i);
if (!contains(list, obj)) {
selectedList.add(obj);
}
}
}
}
return selectedList;
}

public static List<File> getMinusSetFile(List oldList, List list) {
List selectedList = null;
if (oldList != null) {
selectedList = new ArrayList<File>();
int leng = oldList.size();
if (leng != 0) {
for (int i = 0; i < leng; i++) {
Object obj = oldList.get(i);
if (!contains(list, obj)) {
selectedList.add(obj);
}
}
}
}
return selectedList;
}

public static List<String> getMinusSetStr(List oldList, List list) {
List selectedList = null;
if (oldList != null) {
selectedList = new ArrayList<Object>();
int leng = oldList.size();
if (leng != 0) {
for (int i = 0; i < leng; i++) {
Object obj = oldList.get(i);
if (!contains(list, obj)) {
selectedList.add(obj);
}
}
}
}
return selectedList;
}

/***
* 校验MD5 值
* @param file
* @param comparedMD5
* @return
*/
public static boolean getFileMD5(File file,String comparedMD5) {
String md5=getFileMD5(file);
return (md5.equalsIgnoreCase(comparedMD5)&&comparedMD5!=null);
}
/**
* Get MD5 of one file:hex string,test OK!
*
* @param file
* @return : hex string
*/
public static String getFileMD5(File file) {
if (!file.exists() || !file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != NEGATIVE_ONE) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}

public static byte[] digest(byte srcBytes[], String algorithm)
throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(srcBytes);
byte digestBytes[] = digest.digest();
return digestBytes;
}
/***
*
* @param source
* @param charset
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static String getMD5(String source,String charset) throws NoSuchAlgorithmException, UnsupportedEncodingException {
if(ValueWidget.isNullOrEmpty(charset)){
charset=SystemHWUtil.CURR_ENCODING;
}
return getMD5(source.getBytes(charset));
}
public static String getMD5(byte[] source) throws NoSuchAlgorithmException {
byte bytes[] = digest(source, "MD5");
return SystemHWUtil.toHexString(bytes);
}
public static byte[] getMD5Bytes(byte[] source) throws NoSuchAlgorithmException {
byte bytes[] = digest(source, "MD5");
return bytes;
}
public static boolean compareMD5(String source,String charset,String comparedMD5) throws NoSuchAlgorithmException, UnsupportedEncodingException {
String md5=getMD5(source,charset);
return (md5.equalsIgnoreCase(comparedMD5)&&comparedMD5!=null);
}
/***
* Get MD5 of one file!test ok!
*
* @param filepath
* @return
*/
public static String getFileMD5(String filepath) {
File file = new File(filepath);
return getFileMD5(file);
}

/***
* 校验MD5 值
* @param filepath
* @param comparedMD5
* @return
*/
public static boolean getFileMD5(String filepath,String comparedMD5) {
String md5=getFileMD5(filepath);
return (md5.equalsIgnoreCase(comparedMD5)&&comparedMD5!=null);
}
/**
* MD5 encrypt,test ok
*
* @param data
* @return byte[]
* @throws Exception
*/
public static byte[] encryptMD5(byte[] data) throws Exception {

MessageDigest md5 = MessageDigest.getInstance(SystemHWUtil.KEY_MD5);
md5.update(data);
return md5.digest();
}

public static byte[] encryptMD5(String data) throws Exception {
return encryptMD5(data.getBytes(SystemHWUtil.CHARSET_ISO88591));
}

/***
* compare two file by Md5
*
* @param file1
* @param file2
* @return
*/
public static boolean isSameMd5(File file1, File file2) {
String md5_1 = SystemHWUtil.getFileMD5(file1);
String md5_2 = SystemHWUtil.getFileMD5(file2);
return md5_1.equals(md5_2);
}

/***
* compare two file by Md5
*
* @param filepath1
* @param filepath2
* @return
*/
public static boolean isSameMd5(String filepath1, String filepath2) {
File file1 = new File(filepath1);
File file2 = new File(filepath2);
return isSameMd5(file1, file2);
}

/***
* the times target occur in <code>int[] ints</code>
*
* @param ints
* @param target
* @return
*/
public static int count(int[] ints, int target) {
int count = 0;
for (int i = 0; i < ints.length; i++) {
if (ints[i] == target) {
count++;
}
}
return count;
}

/***
* Ignore Case
*
* @param strs
* @param target
* @return
*/
public static int count(String[] strs, String target) {
int count = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i].equalsIgnoreCase(target)) {
count++;
}
}
return count;
}

/***
* Ignore Case
*
* @param list
* @param target
* @return
*/
public static int count(List<String> list, String target) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equalsIgnoreCase(target)) {
count++;
}
}
return count;
}

// public static void printSet(Set<Integer>set ){
// for(Iterator<Integer> it=set.iterator();it.hasNext();){
// Integer age=it.next();
// System.out.println(age);
// }
// }

/***
*
* @param list
*/
public static void printList(List<?> list, boolean isNewline,
String delimiter) {
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
if (isNewline) {
System.out.println(obj);
} else {
System.out.print(obj + delimiter);
}
}
}

public static void printList(List<?> list, String delimiter) {
printList(list, true, delimiter);
}
public static void printList(List list) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException{
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
SystemHWUtil.printObject(obj);
System.out.println(SystemHWUtil.DIVIDING_LINE);
}
}

public static void printStrList(List<String> list) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

public static void printSet(Set<Object> set) {
for (Iterator<Object> it = set.iterator(); it.hasNext();) {
Object age = it.next();
System.out.println(age);
}
}

public static <T extends Serializable> T clone2(T obj) {
T clonedObj = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(
baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
clonedObj = (T) ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return clonedObj;
}

/***
* convert byte array to public key algorithm : RSA
*
* @param keyBytes
*            byte[]
* @return RSAPublicKey
* @throws Exception
*/
public static PublicKey convert2PublicKey(byte[] keyBytes) throws Exception {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory
.getInstance(SystemHWUtil.KEY_ALGORITHM_RSA);// RSA
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
return publicKey;
}

/***
*
* @param keyHexStr
*            : hex(16) string
* @return PublicKey
* @throws Exception
*/
public static PublicKey convert2PublicKey(String keyHexStr)
throws Exception {
byte[] keyBytes = hexStrToBytes(keyHexStr);
return convert2PublicKey(keyBytes);
}

/**
* convert public key to hex(16) bit string
*
* @param publicKey
* @return hex(16) bit string
*/
public static String convert4PublicKey(PublicKey publicKey) {
return toHexString(publicKey.getEncoded());
}

public static PublicKey getPublicKey(InputStream in)
throws CertificateException {
CertificateFactory cf = CertificateFactory
.getInstance(SystemHWUtil.CERTIFICATEFACTORY_X509);
X509Certificate oCertServer = (X509Certificate) cf
.generateCertificate(in);
PublicKey pubKey = oCertServer.getPublicKey();
return pubKey;
}

/***
*
* @param file
* @return
* @throws CertificateException
* @throws FileNotFoundException
*/
public static PublicKey getPublicKey(File file)
throws CertificateException, FileNotFoundException {
InputStream in = new FileInputStream(file);
return getPublicKey(in);
}

/***
*
* @param hex
*            :hex(16) bit string
* @return PublicKey
* @throws CertificateException
*/
public static PublicKey getPublicKey(String hex)
throws CertificateException {
InputStream in = FileUtils.getByteArrayInputSream2hexString(hex);
return getPublicKey(in);
}

/***
*
* @param modulus
*            :N
* @param publicExponent
*            :E
* @return
* @throws Exception
*/
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws Exception {
BigInteger m = new BigInteger(modulus);

BigInteger e = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory keyFactory = KeyFactory
.getInstance(SystemHWUtil.KEY_ALGORITHM_RSA);

PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}

// public static PublicKey getPublicKey(BigInteger m, BigInteger e){
// RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
// KeyFactory keyFactory = KeyFactory
// .getInstance(SystemUtil.KEY_ALGORITHM_RSA);
//
// PublicKey publicKey = keyFactory.generatePublic(keySpec);
// return publicKey;
// }
/***
*
* @param modulus
* @param ePublicExponent
* @return
* @throws Exception
*/
public static PublicKey getPublicKey(BigInteger modulus,
BigInteger ePublicExponent) throws Exception {
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus,
ePublicExponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);

return publicKey;

}

/***
*
* @param m
* @param publicExponent
* @return
* @throws Exception
*/
public static PublicKey getPublicKey(BigInteger m, byte[] publicExponent)
throws Exception {
BigInteger e = new BigInteger(publicExponent);
return getPublicKey(m, e);
}

/**
* convert byte array to private key algorithm : RSA
*
* @param keyBytes
*            byte[]
* @return RSAPrivateKey
* @throws Exception
*/
public static PrivateKey convert2PrivateKey(byte[] keyBytes,
String algorithm) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
return privateKey;
}

/***
*
* @param keyString
*            : hex(16) string
* @return
* @throws Exception
*/
public static PrivateKey convert2PrivateKey(String keyString,
String algorithm) throws Exception {
byte[] keyBytes = hexStrToBytes(keyString);
return convert2PrivateKey(keyBytes, algorithm);
}

/***
* convert private key to hex bit string
*
* @param privateKey
* @return keyString : hex(16) string
*/
public static String convert4PrivateKey(PrivateKey privateKey) {
return toHexString(privateKey.getEncoded());
}

/**
* decrypt,key can be a public key, can also be a private key algorithm :
* RSA
*
* @param message
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] message, Key key) throws Exception {
Cipher cipher = Cipher.getInstance(SystemHWUtil.KEY_ALGORITHM_RSA);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(message);
}

/**
* decrypt,key can be a public key, can also be a private key
*
* @param message
* @return
* @throws Exception
*/
public static byte[] decrypt(String message, Key key) throws Exception {
return SystemHWUtil.decrypt(SystemHWUtil.hexStrToBytes(message), key);
}

/**
* 解密<br>
* 用私钥解密
*
* @param data
* @param publicKeyStr
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, String publicKeyStr,
String algorithm,boolean isHext) throws Exception {
// 对密钥解密
byte[] keyBytes = SystemHWUtil.hexStrToBytes(publicKeyStr);

// 取得公钥
PublicKey publicKey = SystemHWUtil.convert2PublicKey(keyBytes);

return SystemHWUtil.decrypt(data, publicKey);
}

/**
* decrypt use private key to decrypt http://www.5a520.cn
* http://www.feng123.com
*
* @param data
* @param privateKeyStr
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, String privateKeyStr,
String algorithm) throws Exception {
byte[] keyBytes = SystemHWUtil.hexStrToBytes(privateKeyStr);
return decryptByPrivateKey(data, keyBytes, algorithm);
}

public static byte[] decryptByPrivateKey(byte[] data, byte[] keyBytes,
String algorithm) throws Exception {
PrivateKey privateKey = SystemHWUtil.convert2PrivateKey(keyBytes,
algorithm);
return SystemHWUtil.decrypt(data, privateKey);
}

/***
*
* @param data
* @param N
*            :modulus
* @param D
*            :private exponent
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, byte[] N, byte[] D)
throws Exception {
PrivateKey privateKey = getPrivateKey(N, D);
return decrypt(data, privateKey);
}

/***
*
* @param dataHex
*            :hex bit string
* @param privateKeyStr
* @param charSet
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static byte[] decryptByPrivateKey(String dataHex,
String privateKeyStr, String algorithm)
throws UnsupportedEncodingException, Exception {
return decryptByPrivateKey(SystemHWUtil.hexStrToBytes(dataHex),
privateKeyStr, algorithm);
}

/**
* DES
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptDES(byte[] data, byte[] key) throws Exception {
if(ValueWidget.isNullOrEmpty(data)){
return data;
}
// Generate a random number generator which can be trusted
SecureRandom sr = new SecureRandom();

DESKeySpec dks = new DESKeySpec(key);

// Create a key factory, and then use it to convert DESKeySpec to
// SecretKey
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(SystemHWUtil.KEY_ALGORITHM_DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(SystemHWUtil.KEY_ALGORITHM_DES);

cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}

/**
* DES
*
* @param data
* @param key
* @return
* @throws IOException
* @throws Exception
*/
public static String decryptDES(String data, String key)
throws IOException, Exception {
if (data == null)
return null;
byte[] buf = SystemHWUtil.decodeBase64(data);
byte[] bt = SystemHWUtil.decryptDES(buf,
key.getBytes(SystemHWUtil.CHARSET_UTF));
if(bt==null){//data 不是密文
return data;
}
return new String(bt, SystemHWUtil.CHARSET_UTF);
}

/**
* encrypt,key can be a public key,can also be a private key algorithm : RSA
*
* @param message
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] message, Key key) throws Exception {
Cipher cipher = Cipher.getInstance(SystemHWUtil.KEY_ALGORITHM_RSA);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(message);
}

/**
* encrypt,key can be a public key,can also be a private key
*
* @param message
* @return
* @throws Exception
*/
public static byte[] encrypt(String message, Key key) throws Exception {
return SystemHWUtil.encrypt(
message.getBytes(SystemHWUtil.CHARSET_ISO88591), key);
}

/**
* encrypt use public key
*
* @param data
* @param publicKeyStr
*            : hex bit string
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKeyStr)
throws Exception {
byte[] keyBytes = hexStrToBytes(publicKeyStr);
// get public key
PublicKey publicKey = SystemHWUtil.convert2PublicKey(keyBytes);
return SystemHWUtil.encrypt(data, publicKey);
}

/***
*
* @param data
* @param publicKeyStr
*            : hex bit string
* @param charSet
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static byte[] encryptByPublicKey(String data, String publicKeyStr,
String charSet) throws UnsupportedEncodingException, Exception {
return encryptByPublicKey(data.getBytes(charSet), publicKeyStr);
}

/**
* encrypt use private key
*
* @param data
* @param privateKeyStr
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKeyStr,
String algorithm) throws Exception {
byte[] keyBytes = hexStrToBytes(privateKeyStr);
// get private key
Key privateKey = SystemHWUtil.convert2PrivateKey(keyBytes, algorithm);
return SystemHWUtil.encrypt(data, privateKey);
}

/***
*
* @param data
* @param privateKeyStr
*            : hex bit string
* @param charSet
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static byte[] encryptByPrivateKey(String data, String privateKeyStr,
String charSet, String algorithm)
throws UnsupportedEncodingException, Exception {
return encryptByPrivateKey(data.getBytes(charSet), privateKeyStr,
algorithm);
}

/**
* DES
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptDES(byte[] data, byte[] key) throws Exception {
// Generate a random number generator which can be trusted
SecureRandom sr = new SecureRandom();

DESKeySpec dks = new DESKeySpec(key);
// Create a key factory, and then use it to convert DESKeySpec to
// SecretKey
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(SystemHWUtil.KEY_ALGORITHM_DES);
SecretKey securekey = keyFactory.generateSecret(dks);

Cipher cipher = Cipher.getInstance(SystemHWUtil.KEY_ALGORITHM_DES);
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}

/**
* DES
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static String encryptDES(String data, String key) throws Exception {
byte[] bt = SystemHWUtil.encryptDES(
data.getBytes(SystemHWUtil.CHARSET_UTF),
key.getBytes(SystemHWUtil.CHARSET_UTF));
String strs = SystemHWUtil.encodeBase64(bt);
return strs;
}

/**
* use private key sign
*
* @param message
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] sign(byte[] message, PrivateKey privateKey,
SignatureAlgorithm algorithm) throws Exception {
Signature signetcheck = Signature.getInstance(algorithm.getValue());
signetcheck.initSign(privateKey);
signetcheck.update(message);
return signetcheck.sign();
}

/**
* use private key sign
*
* @param message
*            data encrypted
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] sign(String message, PrivateKey privateKey,
SignatureAlgorithm algorithm) throws Exception {
return SystemHWUtil.sign(
message.getBytes(SystemHWUtil.CHARSET_ISO88591), privateKey,
algorithm);
}

/**
* use private key to generate digit sign
*
* @param data
*            data encrypted
* @param privateKeyStr
*            private key
*
* @return
* @throws Exception
*/
public static byte[] sign(byte[] data, String privateKeyStr,
String algorithm, SignatureAlgorithm signatureAlgorithm)
throws Exception {
PrivateKey priKey = SystemHWUtil.convert2PrivateKey(privateKeyStr,
algorithm);
return SystemHWUtil.sign(data, priKey, signatureAlgorithm);
}

/**
*
* @param message
*            data encrypted
* @param privateKeyStr
*            hex(16) string
* @return
* @throws Exception
*/
public static byte[] sign(String message, String privateKeyStr,
String algorithm, SignatureAlgorithm signatureAlgorithm)
throws Exception {
return sign(hexStrToBytes(message), privateKeyStr, algorithm,
signatureAlgorithm);
}

/**
* use public key verify sign
*
* @param message
* @param signStr
* @return
* @throws Exception
*/
public static boolean verifySign(byte[] message, byte[] signBytes,
PublicKey key, SignatureAlgorithm algorithm) throws Exception {
if (message == null || signBytes == null || key == null) {
return false;
}
Signature signetcheck = Signature.getInstance(algorithm.getValue());
signetcheck.initVerify(key);
signetcheck.update(message);
return signetcheck.verify(signBytes);
}

public static boolean verifySign(byte[] message, String signStr,
PublicKey key, SignatureAlgorithm algorithm) throws Exception {
byte[] signBytes = hexStrToBytes(signStr);
return verifySign(message, signBytes, key, algorithm);
}

/**
* use public key verify sign
*
* @algorithm : RSA
* @param message
*            data encrypted
* @param signStr
* @return
* @throws Exception
*/
public static boolean verifySign(String message, String signStr,
PublicKey key, SignatureAlgorithm algorithm) throws Exception {
return SystemHWUtil.verifySign(
message.getBytes(SystemHWUtil.CHARSET_ISO88591),
hexStrToBytes(signStr), key, algorithm);
}

/**
* verify digit sign
*
* @param data
*            date encrypted
* @param publicKeyStr
* @param sign
*
* @return success:true ;fail:false
* @throws Exception
*
*/
public static boolean verifySign(byte[] data, String publicKeyStr,
String sign, SignatureAlgorithm algorithm) throws Exception {
// get public key
PublicKey pubKey = SystemHWUtil.convert2PublicKey(publicKeyStr);

return SystemHWUtil.verifySign(data, sign, pubKey, algorithm);
}

/***
* convert hex(16) bit string to byte array
*
* @param sHex
*            : hex(16) bit string
* @return byte[]
*/
public static final byte[] hexStrToBytes(String sHex) {
int length = sHex.length();
if (length % 2 != 0) {
String message = "Hex  bit string length must be even";
System.err.println(message);
throw new RuntimeException(message);
}
byte[] bytes;
bytes = new byte[sHex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(
sHex.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}

/***
* convert byte array to hex(16) bit string
*
* @param byte[]
* @return hex(16) bit string
*/
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
}
/***
* convert byte array to hex(16) bit string
* @param bytes
* @return
*/
public static String bytes2HexString(byte[]bytes){
return toHexString(bytes);
}

/**
*
* @param byte[]
* @return
* @throws UnsupportedEncodingException
*/
public static String toString(byte[] b) throws UnsupportedEncodingException {
return new String(b, CHARSET_ISO88591);
}

/**
* SHA encrypt
*
* @param data
* @return byte[]
* @throws Exception
*/
public static byte[] encryptSHA(byte[] data) throws Exception {

MessageDigest sha = MessageDigest.getInstance(SystemHWUtil.KEY_SHA);
sha.update(data);
return sha.digest();

}

/***
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptSHA(String data) throws Exception {
return encryptSHA(data.getBytes(SystemHWUtil.CHARSET_ISO88591));
}

/***
* sha-1
*
* @param data
*            byte[]
* @return
* @throws Exception
*/
public static byte[] encryptSHA1(byte[] data) throws Exception {

MessageDigest sha = MessageDigest.getInstance(SystemHWUtil.KEY_SHA1);
sha.update(data);
return sha.digest();

}

/***
* sha-1
*
* @param data
*            :String
* @return
* @throws Exception
*/
public static byte[] encryptSHA1(String data) throws Exception {
return encryptSHA1(data.getBytes(SystemHWUtil.CHARSET_ISO88591));
}

/***
*
* @param secretKey
* @param input
* @param algorithm
* @return byte[]
* @throws Exception
*/
public static byte[] getHMAC(byte[] secretKey, byte[] input,
String algorithm) throws Exception {
Mac mac = Mac.getInstance(algorithm);
// get the bytes of the hmac key and data string
SecretKey secret = new SecretKeySpec(secretKey, algorithm);
mac.init(secret);
// 对input 进行HMAC 加密
byte[] bytesF1 = mac.doFinal(input);
return bytesF1;
}

/***
* HMACSHA256
*
* @param secretKey
* @param input
* @return
* @throws Exception
*/
public static byte[] getHMAC_SHA256(byte[] secretKey, byte[] input)
throws Exception {
return getHMAC(secretKey, input, SystemHWUtil.KEY_HMAC_SHA256);
}

/***
* HmacSHA1
*
* @param secretKey
* @param input
* @return
* @throws Exception
*/
public static byte[] getHMAC_SHA1(byte[] secretKey, byte[] input)
throws Exception {
return getHMAC(secretKey, input, SystemHWUtil.KEY_HMAC_SHA1);
}

/***
*
* @param secretKey
*            : hex bit string
* @param input
*            : hex bit string
* @return byte array
* @throws Exception
*/
public static byte[] getHMAC_SHA1(String secretKey, String input)
throws Exception {
return getHMAC_SHA1(SystemHWUtil.hexStrToBytes(secretKey),
SystemHWUtil.hexStrToBytes(input));
}

/***
*
* @param keyInfo
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static KeyPair getKeyPair(String keyInfo, String algorithm)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
return getKeyPair(keyInfo.getBytes(SystemHWUtil.CHARSET_ISO88591),
algorithm);
}

/***
*
* @param keyInfo
* @param algorithm
*            :算法,如RSA
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static KeyPair getKeyPair(byte[] keyInfo, String algorithm)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
KeyPairGenerator keygen = KeyPairGenerator.getInstance(algorithm);
SecureRandom random = new SecureRandom();
random.setSeed(keyInfo);
// 初始加密,长度为512,必须是大于512才可以的
keygen.initialize(512, random);
// 取得密钥对
KeyPair kp = keygen.generateKeyPair();
return kp;
}

/***
* RSA .
*
* @param keyInfo
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static KeyPair getRSAKeyPair(byte[] keyInfo)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
return getKeyPair(keyInfo, SystemHWUtil.KEY_ALGORITHM_RSA);
}

/***
*
* @param modulus
*            :N
* @param privateExponent
*           
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(String modulus,
String privateExponent) throws Exception {

BigInteger m = new BigInteger(modulus);

BigInteger D = new BigInteger(privateExponent);

RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, D);

KeyFactory keyFactory = KeyFactory
.getInstance(SystemHWUtil.KEY_ALGORITHM_RSA);

PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

return privateKey;

}

/***
*
* @param m
*            : modulus
* @param d
*            :private exponent
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(BigInteger m, BigInteger d)
throws Exception {
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, d);

KeyFactory keyFactory = KeyFactory
.getInstance(SystemHWUtil.KEY_ALGORITHM_RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

return privateKey;

}

// public static PrivateKey getPrivateKey(byte[] N_hex, byte[] D_hex){
// return SystemUtil.getPrivateKey(new BigInteger(N_hex), new
// BigInteger(D_hex));
// }
/***
*
* @param m
* @param privateExponent
*           
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(BigInteger m, byte[] privateExponent)// TODO
throws Exception {
BigInteger d = new BigInteger(privateExponent);
return getPrivateKey(m, d.negate());
}

public static PrivateKey getPrivateKey(byte[] m, byte[] privateExponent)
throws Exception {
return getPrivateKey(SystemHWUtil.getBigIntegerByByteArr(m),
SystemHWUtil.getBigIntegerByByteArr(privateExponent));
}

/***
* OK
*
* @param publicKey
* @param priKey
* @return
* @throws Exception
*/
public static boolean verifyPrivPubKey(PublicKey publicKey,
PrivateKey priKey) throws Exception {
String message = "32";
RSAPublicKey rsaPublKey = (RSAPublicKey) publicKey;
RSAPrivateKey rsaPriKey = (RSAPrivateKey) priKey;
byte[] encryptBytes = SystemHWUtil.encrypt(message, publicKey);
byte[] decryptBytes = SystemHWUtil.decrypt(encryptBytes, priKey);
return new String(decryptBytes, SystemHWUtil.CHARSET_ISO88591)
.equals(message)
&& rsaPriKey.getModulus().equals(rsaPublKey.getModulus());
}

/***
* OK
*
* @param m
*            :modulus
* @param e
*            :public key publicExponent
* @param d
*            :private exponent
* @return
* @throws Exception
*/
public static boolean verifyPrivPubKey(BigInteger modulus,
BigInteger publicExponent, BigInteger privateExponent)
throws Exception {
PublicKey pubKey = getPublicKey(modulus, publicExponent);
PrivateKey priKey = getPrivateKey(modulus, privateExponent);
return SystemHWUtil.verifyPrivPubKey(pubKey, priKey);
}

public static boolean verifyPrivPubKey(String modulus_decimal,
String publicExponent_decimal, String privateExponent_decimal)
throws Exception {
BigInteger modulus = new BigInteger(modulus_decimal);
BigInteger publicExponent = new BigInteger(publicExponent_decimal);
BigInteger privateExponent = new BigInteger(privateExponent_decimal);
return verifyPrivPubKey(modulus, publicExponent, privateExponent);
}

/***
* convert byte array to BigInteger
*
* @param bytes
* @return
*/
public static BigInteger getBigIntegerByByteArr(byte[] bytes) {
return new BigInteger(SystemHWUtil.toHexString(bytes), 16);
}

/***
* convert BigInteger to byte array
*
* @param bi
* @return
*/
public static byte[] getBytesByBigInteger(BigInteger bi) {
String hexString = bi.toString(16);
return SystemHWUtil.hexStrToBytes(hexString);
}

/***
* get prime number
*
* @param base
* @return
*/
// public static int generatePrime(int base) {
// for (int i = base;; i++) {
// if (isPrime(i)) {
// return i;
// }
// }
// }
/***
* get prime number which >=base,result>=base
*
* @param base
* @return
*/
public static BigInteger generatePrime(int base) {
return generatePrime(BigInteger.valueOf(base));
}

/***
* convert decemal string to BigInteger. radix:10
*
* @param dicemalBase
* @return
*/
public static BigInteger generatePrime(String dicemalBase) {
return generatePrime(new BigInteger(dicemalBase, 10));
}

/***
* get prime number which >=base
*
* @param base
* @return BigInteger
*/
public static BigInteger generatePrime(BigInteger base) {
for (BigInteger i = base;; i = i.add(BIGINT1)) {
if (isPrime(i)) {
return i;
}
}
}

/***
* whether is a prime number
*
* @param num
* @return
*/
public static boolean isPrime(int num) {
return isPrime(BigInteger.valueOf(num));
// boolean isPrime = true;
// for (int i = 2; i <= num / 2; i++) {
// if (num % i == 0) {
// isPrime = false;
// break;
// }
// }
// return isPrime;
}

/***
* whether is a prime number
*
* @param num
* @return
*/
public static boolean isPrime(BigInteger num) {
boolean isPrime = true;
BigInteger bigIntTwo = BigInteger.valueOf(2l);
BigInteger bigIntOne = BIGINT1;
for (BigInteger i = bigIntTwo; num.divide(bigIntTwo).compareTo(i) >= 0; i = i
.add(bigIntOne)) {
if (num.mod(i).intValue() == 0) {
isPrime = false;
break;
}
}
return isPrime;
}

/***
*
* @param ta
* @param isAdd
*/
public static void addSubduction(JTextArea ta, boolean isAdd) {
String argument1 = ta.getText();
BigInteger bigIntArg1 = new BigInteger(argument1);
if (isAdd) {
ta.setText(bigIntArg1.add(BIGINT1).toString());
} else {
ta.setText(bigIntArg1.subtract(BIGINT1).toString());
}
}

/***
*
* @param tf
* @param isAdd
*/
public static void addSubduction(JTextField tf, boolean isAdd) {
String argument1 = tf.getText();
BigInteger bigIntArg1 = new BigInteger(argument1);
if (isAdd) {
tf.setText(bigIntArg1.add(BIGINT1).toString());
} else {
tf.setText(bigIntArg1.subtract(BIGINT1).toString());
}
}

/***
*
* @param ta
* @return
*/
public static BigInteger getBigInteger(JTextArea ta) {
String data = ta.getText();
return new BigInteger(data);
}

/***
*
* @param arg1
* @param arg2
* @return
*/
public static BigInteger mod(BigInteger arg1, BigInteger arg2) {
return arg1.mod(arg2);
}

/***
*
* @param ta1
* @param ta2
* @return
*/
public static BigInteger mod(JTextArea ta1, JTextArea ta2) {
BigInteger arg1 = new BigInteger(ta1.getText());
BigInteger arg2 = new BigInteger(ta2.getText());
return mod(arg1, arg2);
}

/***
*
* @param ta1
* @param ta2
* @return
*/
public static BigInteger mod(JTextField ta1, JTextField ta2) {
BigInteger arg1 = new BigInteger(ta1.getText());
BigInteger arg2 = new BigInteger(ta2.getText());
return mod(arg1, arg2);
}

/***
* convert int to hex string
*
* @param bigInt
* @return
*/
public static String toHexString(BigInteger bigInt) {
return bigInt.toString(16);
}

/***
*
* @param ta
* @return
*/
public static String toHexString(JTextArea ta) {
BigInteger arg1 = new BigInteger(ta.getText());
return toHexString(arg1);

}

/***
* encode by Base64
*/
public static String encodeBase64(byte[] input) throws Exception {
Class clazz = Class
.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod = clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
Object retObj = mainMethod.invoke(null, new Object[] { input });
return (String) retObj;
}

/***
* decode by Base64
*/
public static byte[] decodeBase64(String input) throws Exception {
Class clazz = Class
.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod = clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj = mainMethod.invoke(null, input);
return (byte[]) retObj;
}

/**
* 编码
*
* @param bstr
* @return String
*/
public static String encode(byte[] bstr) {
return new sun.misc.BASE64Encoder().encode(bstr);
}

/**
* 解码
*
* @param str
* @return string
*/
public static byte[] decode(String str) {
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}

return bt;
}

/***
* 获取实际的子类的class
*
* @param clz
* @return
*/
public static <T> Class<T> getGenricClassType(
@SuppressWarnings("rawtypes") Class clz) {
Type type = clz.getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type[] types = pt.getActualTypeArguments();
if (types.length > 0 && types[0] instanceof Class) {
// System.out.println("class:"+types[0]);
return (Class) types[0];
}
}

return (Class) Object.class;
}

// public static byte[] decodeBufferBASE64Decoder(String data) {
//
// try {
// Class clazz = Class.forName("sun.misc.BASE64Decoder");
// Method mainMethod;
// mainMethod = clazz.getMethod("decodeBuffer", String.class);
// mainMethod.setAccessible(true);
// Object retObj = mainMethod.invoke(clazz.newInstance(), data);
// return (byte[]) retObj;
// } catch (SecurityException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
// return null;
//
// }
//
// public static String encodeBASE64Encoder(byte[] bt) {
//
// try {
// Class clazz = Class.forName("sun.misc.BASE64Decoder");
// Method mainMethod;
// mainMethod = clazz.getMethod("encode", byte[].class);
// mainMethod.setAccessible(true);
// Object retObj = mainMethod.invoke(clazz.newInstance(), bt);
// return (String) retObj;
// } catch (SecurityException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
// return null;
//
// }
/***
* print byte array
*
* @param bytes
* @param isNeedPlus
*            : Whether to add a plus sign
* @return such as
*         "[ 52, 116, -18, 34, 70, -43,  56, -60, 17, -67, -52, -97 ] ;length:16"
*/
public static String printBytes(byte[] bytes, boolean isNeedPlus) {
StringBuffer sb = new StringBuffer("[ ");
for (int i = 0; i < bytes.length; i++) {

if (bytes[i] > 0 && isNeedPlus) {
sb.append("+" + String.valueOf(bytes[i]));
} else {
sb.append(bytes[i]);
}
if (i < bytes.length - 1) {
sb.append(", ");
}
}
sb.append(" ]").append(" ;length:" + bytes.length);
return sb.toString();
}

/***
* Format a byte array
*
* @param bytes
* @return
*/
public static String formatBytes(byte[] bytes) {
return printBytes(bytes, false);
}
/***
* convert Set to String[]
* @param set
* @since 2014-07-17
* @return
*/
public static String[]formatSet(Set set){
if(ValueWidget.isNullOrEmpty(set)){
return null;
}
String[]strs=new String[set.size()];
int count=0;
for (Iterator<?> it = set.iterator(); it.hasNext();) {
String childType22 = (String) it.next();
strs[count++]=childType22;
}
return strs;
}
/***
* 把数组转化为Set
* @param strs
* @return
*/
public static Set convert2Set(String[]strs){
if(ValueWidget.isNullOrEmpty(strs)){
return null;
}
Set set=new HashSet();
for(int i=0;i<strs.length;i++){
set.add(strs[i]);
}
return set;
}

/***
* Format a byte array
*
* @param hex
* @return
*/
public static String formatBytes(String hex) {
return formatBytes(SystemHWUtil.hexStrToBytes(hex));
}

/***
*
* @param bytes
*/
public static void printBytes(byte[] bytes) {
System.out.println(formatBytes(bytes));
}

/***
*
* @param hex
*/
public static void printBytes(String hex) {
System.out.println(formatBytes(hex));
}

/***
* 合并字节数组
*
* @param a
* @return
*/
public static byte[] mergeArray(byte[]... a) {
// 合并完之后数组的总长度
int index = 0;
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i].length;
}
byte[] result = new byte[sum];
for (int i = 0; i < a.length; i++) {
int lengthOne = a[i].length;
if (lengthOne == 0) {
continue;
}
// 拷贝数组
System.arraycopy(a[i], 0, result, index, lengthOne);
index = index + lengthOne;
}
return result;
}

/***
* 联合成为路径
* @param parent
* @param child
* @return
*/
public static String mergeTwoPath(String parent,String child){
String fullPath;
if (!child.startsWith("\\") && !parent.endsWith("\\")) {
fullPath = parent + "\\" + child;
} else {
fullPath = parent + child;
}
return fullPath;
}
/***
* merge two array
* @param arr1
* @param arr2
* @return
*/
public static String[] mergeArray2(String[]arr1,String[]arr2){
int length1=arr1.length;
int length2=arr2.length;
int totalLength=length1+length2;
String[]totalArr=new String[totalLength];
for(int i=0;i<length1;i++){
totalArr[i]=arr1[i];
}
for(int i=0;i<length2;i++){
totalArr[i+length1]=arr2[
2 楼 hellohank 2015-08-17  
使用正则容易出现:性能问题,和一些诡异的错误。建议:要么使用现有的Html解析框架(如Jsoup、HtmlParser等),要么使用栈的方式来实现~
1 楼 mikzhang 2015-08-17  
SystemHWUtil 的代码贴出来

相关推荐

Global site tag (gtag.js) - Google Analytics