KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dlog4j > util > StringUtils


1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU Library General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  */

16 package dlog4j.util;
17
18 import java.security.*;
19 import java.util.regex.Matcher JavaDoc;
20 import java.util.regex.Pattern JavaDoc;
21
22 import javax.crypto.Cipher;
23 import javax.crypto.SecretKey;
24 import javax.crypto.SecretKeyFactory;
25 import javax.crypto.spec.DESKeySpec;
26
27 /**
28  * 字符串工具集合
29  * 此类需要JRE 1.4
30  * @author Liudong
31  */

32 public class StringUtils extends org.apache.commons.lang.StringUtils{
33
34     private static final String JavaDoc PASSWORD_CRYPT_KEY = "__jDlog_";
35     private final static String JavaDoc DES = "DES";
36     
37     static Pattern JavaDoc emailer;
38     
39     /**
40      * 判断是不是一个合法的电子邮件地址
41      * @param email
42      * @return
43      */

44     public static boolean isEmail(String JavaDoc email){
45         if(emailer==null){
46             String JavaDoc check = "^([a-z0-9A-Z]+[-|\\._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
47             emailer = Pattern.compile(check);
48         }
49         Matcher JavaDoc matcher = emailer.matcher(email);
50         return matcher.matches();
51     }
52     /**
53      * 加密
54      * @param src 数据源
55      * @param key 密钥,长度必须是8的倍数
56      * @return 返回加密后的数据
57      * @throws Exception
58      */

59     public static byte[] encrypt(byte[] src, byte[] key)
60         throws Exception JavaDoc {
61         // DES算法要求有一个可信任的随机数源
62
SecureRandom sr = new SecureRandom();
63         // 从原始密匙数据创建DESKeySpec对象
64
DESKeySpec dks = new DESKeySpec(key);
65         // 创建一个密匙工厂,然后用它把DESKeySpec转换成
66
// 一个SecretKey对象
67
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
68         SecretKey securekey = keyFactory.generateSecret(dks);
69         // Cipher对象实际完成加密操作
70
Cipher cipher = Cipher.getInstance(DES);
71         // 用密匙初始化Cipher对象
72
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
73         // 现在,获取数据并加密
74
// 正式执行加密操作
75
return cipher.doFinal(src);
76     }
77     
78     /**
79      * 解密
80      * @param src 数据源
81      * @param key 密钥,长度必须是8的倍数
82      * @return 返回解密后的原始数据
83      * @throws Exception
84      */

85     public static byte[] decrypt(byte[] src, byte[] key)
86         throws Exception JavaDoc {
87         // DES算法要求有一个可信任的随机数源
88
SecureRandom sr = new SecureRandom();
89         // 从原始密匙数据创建一个DESKeySpec对象
90
DESKeySpec dks = new DESKeySpec(key);
91         // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
92
// 一个SecretKey对象
93
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
94         SecretKey securekey = keyFactory.generateSecret(dks);
95         // Cipher对象实际完成解密操作
96
Cipher cipher = Cipher.getInstance(DES);
97         // 用密匙初始化Cipher对象
98
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
99         // 现在,获取数据并解密
100
// 正式执行解密操作
101
return cipher.doFinal(src);
102     }
103     /**
104      * 密码解密
105      * @param data
106      * @return
107      * @throws Exception
108      */

109     public final static String JavaDoc decrypt(String JavaDoc data){
110         try {
111             return new String JavaDoc(decrypt(hex2byte(data.getBytes()),PASSWORD_CRYPT_KEY.getBytes()));
112         }catch(Exception JavaDoc e) {
113         }
114         return null;
115     }
116     /**
117      * 密码加密
118      * @param password
119      * @return
120      * @throws Exception
121      */

122     public final static String JavaDoc encrypt(String JavaDoc password){
123         try {
124             return byte2hex(encrypt(password.getBytes(),PASSWORD_CRYPT_KEY.getBytes()));
125         }catch(Exception JavaDoc e) {
126         }
127         return null;
128     }
129     /**
130      * 二行制转字符串
131      * @param b
132      * @return
133      */

134     public static String JavaDoc byte2hex(byte[] b) {
135         String JavaDoc hs = "";
136         String JavaDoc stmp = "";
137         for (int n = 0; n < b.length; n++) {
138             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
139             if (stmp.length() == 1)
140                 hs = hs + "0" + stmp;
141             else
142                 hs = hs + stmp;
143         }
144         return hs.toUpperCase();
145     }
146     
147     public static byte[] hex2byte(byte[] b) {
148         if((b.length%2)!=0)
149             throw new IllegalArgumentException JavaDoc("长度不是偶数");
150         byte[] b2 = new byte[b.length/2];
151         for (int n = 0; n < b.length; n+=2) {
152             String JavaDoc item = new String JavaDoc(b,n,2);
153             b2[n/2] = (byte)Integer.parseInt(item,16);
154         }
155         return b2;
156     }
157     
158     /**
159      * 大小写无关的字符串替换策略
160      * @param str
161      * @param src
162      * @param obj
163      * @return
164      */

165     public static String JavaDoc replaceIgnoreCase(String JavaDoc str, String JavaDoc src, String JavaDoc obj){
166         String JavaDoc l_str = str.toLowerCase();
167         String JavaDoc l_src = src.toLowerCase();
168         int fromIdx = 0;
169         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
170         do{
171             int idx = l_str.indexOf(l_src, fromIdx);
172             if(idx==-1)
173                 break;
174             result.append(str.substring(fromIdx, idx));
175             result.append(obj);
176             fromIdx = idx + src.length();
177         }while(true);
178         result.append(str.substring(fromIdx));
179         return result.toString();
180     }
181     
182     public static void main(String JavaDoc[] args) {
183         String JavaDoc pwd = "测试dasdfaaaaaaa";
184         String JavaDoc data = encrypt(pwd);
185         System.out.println("data="+data);
186         pwd = decrypt(data);
187         System.out.println("pwd="+pwd);
188         
189         System.out.println(replaceIgnoreCase("public class StringUtilsTest extends TestCase","clAss","inTerface"));
190     }
191 }
Popular Tags