import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
/**
* 二行制转十六进制字串
*/
public static String byte2hex(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
/**
* 十六进制字串转二进制数组
*/
public static byte[] hex2byte(String hexStr) {
byte[] b = hexStr.getBytes();
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;
}
/**
* 计算md5码. 以MD5 32位输出
*/
public static byte[] getMD5Hash(byte[] data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data);
return md.digest();
}
/**
* @param keyBytes key
* @param dataBytes 要加密/解密的数据
* @param algorithmDes 填充方式,
* @param ivBytes 向量,可为空. 在DES_ECB填充模式中无法使用向量
* @param mode 加密解密模式
* @return 加密/解密后的byte数组
*/
public static byte[] des(byte[] keyBytes, byte[] dataBytes, String algorithmDes, byte[] ivBytes, int mode) {
if (dataBytes == null) {
return null;
}
try {
assert keyBytes.length >= 8;
DESKeySpec dks = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(algorithmDes);
if (ivBytes != null) {
cipher.init(mode, secretKey, new IvParameterSpec(ivBytes));
} else {
cipher.init(mode, secretKey);
}
return cipher.doFinal(dataBytes);
} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
e.printStackTrace();
return null;
}
}