package bishe;import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;public class DesEncrypt {
Key key;
public static byte binary[];
byte[] des_tt;
byte[] gt;
byte[] r;
int msg2_size;
byte[] data;
String content; public DesEncrypt() {
super();
// TODO Auto-generated constructor stub
} /**
 * 生成KEY
 */
public void getKey(String strKey) {
try { KeyGenerator _generator = KeyGenerator.getInstance("DES");
_generator.init(new SecureRandom(strKey.getBytes()));
this.key = _generator.generateKey();
_generator = null;
} catch (Exception e) {
e.printStackTrace();
}
} /**
 * 加密String明文输入,byte[]密文输出
 */
public byte[] getEncString(String strMing) {
Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1);
des_tt = null;
int[] tt = null;
byte[] strMi = strMing.getBytes();
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
des_tt = cipher.doFinal(strMi);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
int tti = 0;
System.out.println(des_tt);
// 正式把des加密信息的byte数组转化为二进制的数组tt[]
binary = new byte[8 * (des_tt.length)];
for (int t = 0; t < des_tt.length; t++) {
int temp = des_tt[t] + 128;
for (int ba = 0; ba < 8; ba++) {
if (temp == 0) {
binary[tti] = 0;
} else {
binary[tti] = (byte) (temp % 2);
temp = ((temp & 0xff) >> 1);
}
tti++;
}
}
System.out.print("转化为二进制后的tt[n]数组数值为:");
for (int n = 0; n < binary.length; n++) {
System.out.print(binary[n]);
}
System.out.println();
return binary; } /**
 * 解密 以byte[]密文输入,String明文输出
 * 
 * @param strMi
 */
public String getDesString(String strMi) { String strMing;
String regEx = "</?[a-zA-Z][^>]*>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(strMi);
byte[] gt_temp = new byte[16];
int i = 0; String temp = m.group();
char ch_temp[] = temp.toCharArray();
int index = 0;
if (ch_temp[index] >= 'a' && ch_temp[index] <= 'z') { if (i < msg2_size * 8) {
gt[i] = 0;
i++;
} else if (ch_temp[index] >= 'A' && ch_temp[index] <= 'Z') {
if (i < msg2_size * 8) {
gt[i] = 1;
i++;
}
}
r = new byte[gt.length / 8];
//解密
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
data = cipher.doFinal(r);
} catch (Exception e) {
e.printStackTrace();
}
}
strMing = new String(data);
System.out.println("解密之后的结果是: " + strMing);
return strMing;
} public static void main(String args[]) {
DesEncrypt des = new DesEncrypt();
des.getKey("hello");
byte[] aa = des.getEncString("中南林");

des.getDesString("0010110101010011011001011010011010010100100011000000110111100110");
}
}