JAVA DES/ECB/PKCS7Padding 加解密算法
直接上代码
package com.api.hbBussiness;
public class DesUtil {
private static Map<String, String> secretkeyMap = new HashMap();
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS7Padding";
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
private static Cipher GetCipher(int opmode, String key) {
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(opmode, secretKey);
return cipher;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String encode(String data, String key) {
if (data == null || data.isEmpty())
return null;
try {
Cipher cipher = GetCipher(Cipher.ENCRYPT_MODE, key);
if (cipher == null) {
return null;
} else {
byte[] byteHex = cipher.doFinal(data.getBytes("UTF-8"));
return byteToHexString(byteHex);
}
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
public static String decode(String data, String key) throws Exception {
if (data == null || data.isEmpty()) {
return null;
}
try {
byte[] b = hex2byte(data);
Cipher cipher = GetCipher(Cipher.DECRYPT_MODE, key);
if (cipher != null) {
return new String(cipher.doFinal(b), "UTF-8");
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
public static String byteToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer(bytes.length);
String sTemp;
for (int i = 0; i < bytes.length; i++) {
sTemp = Integer.toHexString(0xFF & bytes[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static String encode(byte[] src) {
String strHex = "";
StringBuilder sb = new StringBuilder("");
for (int n = 0; n < src.length; n++) {
strHex = Integer.toHexString(src[n] & 0xFF);
sb.append((strHex.length() == 1) ? "0" + strHex : strHex);
}
return sb.toString().trim();
}
public static byte[] hex2byte(String hex) throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException("invalid hex string");
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
}
return b;
}
}