public final classDesUtils {private static final String DES = "DES";private static final String KEY = "4YztMHI7PsT4rLZN";privateDesUtils() {}private static byte[] encrypt(byte[] src, byte[] key) throwsException {
SecureRandom sr= newSecureRandom();
DESKeySpec dks= newDESKeySpec(key);
SecretKeyFactory keyFactory=SecretKeyFactory.getInstance(DES);
SecretKey secretKey=keyFactory.generateSecret(dks);
Cipher cipher=Cipher.getInstance(DES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);returncipher.doFinal(src);
}private static byte[] decrypt(byte[] src, byte[] key) throwsException {
SecureRandom sr= newSecureRandom();
DESKeySpec dks= newDESKeySpec(key);
SecretKeyFactory keyFactory=SecretKeyFactory.getInstance(DES);
SecretKey secretKey=keyFactory.generateSecret(dks);
Cipher cipher=Cipher.getInstance(DES);
cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);returncipher.doFinal(src);
}private static String byte2hex(byte[] b) {
String hs= "";
String temp= "";for (int n = 0; n < b.length; n++) {
temp= (java.lang.Integer.toHexString(b[n] & 0XFF));if (temp.length() == 1)
hs= hs + "0" +temp;elsehs= hs +temp;
}returnhs.toUpperCase();
}private static byte[] hex2byte(byte[] b) {if ((b.length % 2) != 0)throw new IllegalArgumentException("length not even");byte[] b2 = new byte[b.length / 2];for (int n = 0; n < b.length; n += 2) {
String item= new String(b, n, 2);
b2[n/ 2] = (byte) Integer.parseInt(item, 16);
}returnb2;
}private staticString decode(String src, String key) {
String decryptStr= "";try{byte[] decrypt =decrypt(hex2byte(src.getBytes()), key.getBytes());
decryptStr= newString(decrypt);
}catch(Exception e) {
e.printStackTrace();
}returndecryptStr;
}private staticString encode(String src, String key){byte[] bytes = null;
String encryptStr= "";try{
bytes=encrypt(src.getBytes(), key.getBytes());
}catch(Exception ex) {
ex.printStackTrace();
}if (bytes != null)
encryptStr=byte2hex(bytes);returnencryptStr;
}/*** 解密*/
public staticString decode(String src) {returndecode(src, KEY);
}/*** 加密*/
public staticString encode(String src) {returnencode(src, KEY);
}
}