null==charset||"".equals(charset)) {
69 md.update(str.getBytes());
70 }else{
71 md.update(str.getBytes(charset));
72 }
73 //得到该摘要
74 bytes = md.digest();
75 } catch (NoSuchAlgorithmException e) {
76 System.out.println("加密算法: "+ algorithm +" 不存在: ");
77 } catch (UnsupportedEncodingException e) {
78 System.out.println("数据加密指定的编码格式不支持: " + charset);
79 }
80 return null==bytes?null:bytes;
81 }
82 /**
83 * 把字节数组转化成字符串返回
84 * @param bytes
85 * @return
86 */
87 public static String BytesConvertToHexString(byte [] bytes) {
88 StringBuffer sb = new StringBuffer();
89 for (byte aByte : bytes) {
90 String s=Integer.toHexString(0xff & aByte);
91 if(s.length()==1){
92 sb.append("0"+s);
93 }else{
94 sb.append(s);
95 }
96 }
97 return sb.toString();
98 }
99
100 //测试上述方法
101 public static void main(String[] args) {
102 String test1="test1";
103 String test2="QWERFVDSCX";
104 String test3="23423KJHkdfg";
105 String [] test={test1,test2,test3};
106 for (String s : test) {
107 String str=EncryptionStr32(s, MD5, UTF8);
108 System.out.println("数据:" + s+" 加密之后的结果为:"+str+" 字符串长度为:"+str.length());
109 str = EncryptionStr16(s, MD5, UTF8);
110 System.out.println("数据:" + s+" 加密之后的结果为:"+str+" 字符串长度为:"+str.length());
111 }
112 }
113 }