import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DecStr {
public static void main(String args[]) throws Exception {
String jiami = Encrypt("中国人民解放军henniuhenniudi", "26451d8f");
System.out.println("加密:" + jiami);
String jiemi = Decrypt(jiami, "26451d8f");
System.out.println("解密:" + jiemi);
}
/**
* DES算法,解密
*
* @param message 待解密字符串
* @param key 解密私钥,长度不能够小于8位
* @return 解密后的字节数组
* @throws Exception 异常
*/
public static String Decrypt(String message, String key)
throws Exception {
// base64 + des 解密
// BASE64Decoder base64Decoder = new BASE64Decoder();
// byte[] bytesrc=base64Decoder.decodeBuffer(message);
byte[] bytesrc = hex2byte(message.getBytes()); // 不用base64 的方式
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("ISO-8859-1"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("ISO-8859-1"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
}
/**
* DES算法,加密
*
* @param message 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
* @throws CryptException 异常
*/
public static String Encrypt(String message, String key)
throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("ISO-8859-1"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("ISO-8859-1"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encryptbyte = cipher.doFinal(message.getBytes());
// BASE64Encoder base64Encoder = new BASE64Encoder();
// base64Encoder.encode(encryptbyte);
// return base64Encoder.encode(encryptbyte);
return byte2hex(encryptbyte);
}
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
public static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");
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);
}
return b2;
}
}