|
package com.flow.util;
|
|
import java.security.SecureRandom;
|
import javax.crypto.Cipher;
|
import javax.crypto.SecretKey;
|
import javax.crypto.SecretKeyFactory;
|
import javax.crypto.spec.DESKeySpec;
|
import org.apache.commons.codec.binary.Base64;
|
|
public class DESUtil {
|
public static final String KEY_ALGORITHM = "DES";
|
public static final String CIPHER_ALGORITHM = "DESede/CBC/PKCS5Padding";
|
public static String key = "FHGT4KHVJKVKV2KHCTBM";
|
|
public DESUtil() {
|
}
|
|
private static SecretKey keyGenerator(String keyStr) throws Exception {
|
byte[] input = HexString2Bytes(keyStr);
|
DESKeySpec desKey = new DESKeySpec(input);
|
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
|
SecretKey securekey = keyFactory.generateSecret(desKey);
|
return securekey;
|
}
|
|
private static int parse(char c) {
|
if (c >= 'a') {
|
return c - 97 + 10 & 15;
|
} else {
|
return c >= 'A' ? c - 65 + 10 & 15 : c - 48 & 15;
|
}
|
}
|
|
public static byte[] HexString2Bytes(String hexstr) {
|
byte[] b = new byte[hexstr.length() / 2];
|
int j = 0;
|
|
for(int i = 0; i < b.length; ++i) {
|
char c0 = hexstr.charAt(j++);
|
char c1 = hexstr.charAt(j++);
|
b[i] = (byte)(parse(c0) << 4 | parse(c1));
|
}
|
|
return b;
|
}
|
|
public static String encrypt(String data, String key) throws Exception {
|
SecureRandom sr = new SecureRandom();
|
DESKeySpec dks = new DESKeySpec(key.getBytes());
|
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
|
SecretKey securekey = keyFactory.generateSecret(dks);
|
Cipher cipher = Cipher.getInstance("DES");
|
cipher.init(1, securekey, sr);
|
byte[] results = cipher.doFinal(data.getBytes());
|
return Base64.encodeBase64String(results);
|
}
|
|
public static String decrypt(String data, String key) throws Exception {
|
SecureRandom sr = new SecureRandom();
|
DESKeySpec dks = new DESKeySpec(key.getBytes());
|
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
|
SecretKey securekey = keyFactory.generateSecret(dks);
|
Cipher cipher = Cipher.getInstance("DES");
|
cipher.init(2, securekey, sr);
|
return new String(cipher.doFinal(Base64.decodeBase64(data)));
|
}
|
|
public static void main(String[] args) throws Exception {
|
String url = "jdbc:mysql://localhost:3306/hxzkflow?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true";
|
String username = "15210640466";
|
String password = "123456";
|
System.out.println("url: " + url);
|
System.out.println("username: " + username);
|
System.out.println("password: " + password);
|
String e_url = encrypt(url, key);
|
String e_username = encrypt(username, key);
|
String e_password = encrypt(password, key);
|
System.out.println("加密后url: " + e_url);
|
System.out.println("加密后username: " + e_username);
|
System.out.println("加密后password: " + e_password);
|
}
|
}
|