packagecom.blog.d201706.encrypt;importjavax.crypto.Cipher;importjavax.crypto.SecretKey;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.DESKeySpec;importjavax.crypto.spec.IvParameterSpec;public classDes {/*** 加密
*@paramdata
*@paramsKey
*@return
*/
public static byte[] encrypt(byte[] data, String sKey) {try{byte[] key =sKey.getBytes();//初始化向量
IvParameterSpec iv = newIvParameterSpec(key);
DESKeySpec desKey= newDESKeySpec(key);//创建一个密匙工厂,然后用它把DESKeySpec转换成securekey
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey=keyFactory.generateSecret(desKey);//Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);//现在,获取数据并加密//正式执行加密操作
returncipher.doFinal(data);
}catch(Throwable e) {
e.printStackTrace();
}return null;
}/*** 解密
*@paramsrc
*@paramsKey
*@return*@throwsException*/
public static byte[] decrypt(byte[] src, String sKey) throwsException {byte[] key =sKey.getBytes();//初始化向量
IvParameterSpec iv = newIvParameterSpec(key);//创建一个DESKeySpec对象
DESKeySpec desKey = newDESKeySpec(key);//创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");//将DESKeySpec对象转换成SecretKey对象
SecretKey securekey =keyFactory.generateSecret(desKey);//Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");//用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, iv);//真正开始解密操作
returncipher.doFinal(src);
}/*** 将二进制转换成16进制
*
*@parambuf
*@return
*/
public static String parseByte2HexStr(bytebuf[]) {
StringBuffer sb= newStringBuffer();for (int i = 0; i String hex= Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {
hex= '0' +hex;
}
sb.append(hex.toUpperCase());
}returnsb.toString();
}/*** 将16进制转换为二进制
*
*@paramhexStr
*@return
*/
public static byte[] parseHexStr2Byte(String hexStr) {if (hexStr.length() <1) return null;byte[] result &#61; new byte[hexStr.length() / 2];for (int i &#61; 0; i result[i]&#61; (byte) (high * 16 &#43;low);
}returnresult;
}
}