package aisino.comm;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
*
* DES加密工具类
*/
public class DESUtil {
private static final String TAG = "TAG";
/**
* 生成密钥
*/
public static byte[] initKey() {
try {
//KeyGenerator 密钥生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
//初始化密钥生成器
keyGenerator.init(56);
//生成密钥
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
} catch (Exception e) {
//Log.e(TAG, "initKey: " + e.getMessage());
}
return null;
}
/**
* DES加密
*
* @param data 需要加密的数据
* @param key 加密使用的密钥
* @return 加密后获取的字节数组
*/
public static byte[] encrypt(byte[] data, byte[] key) {
//恢复密钥
SecretKey secretKey = new SecretKeySpec(key, "DES");
try {
//Cipher完成加密或解密工作
Cipher cipher = Cipher.getInstance("DES");
//根据密钥对Cipher进行初始化 ENCRYPT_MODE, DECRYPT_MODE
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//加密
return cipher.doFinal(data);
} catch (Exception e) {
// Log.e(TAG, "encrypt: " + e.getMessage());
}
return null;
}
/**
* DES解密
*/
/**
* @param data 密文对应的字节数组
* @param key 算法名字
* @return 解密后的字节数组
*/
public static byte[] decrypt(byte[] data, byte[] key) {
SecretKey secretKey = new SecretKeySpec(key, "DES");
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (Exception e) {
//Log.e(TAG, "decrypt: " + e.getMessage());
}
return null;
}
public static String byteArrayToHexStr(byte[] byteArray) {
if (byteArray == null){
return null;
}
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[byteArray.length * 2];
for (int j = 0; j < byteArray.length; j++) {
int v = byteArray[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexStrToByteArray(String str)
{
if (str == null) {
return null;
}
if (str.length() == 0) {
return new byte[0];
}
byte[] byteArray = new byte[str.length() / 2];
for (int i = 0; i < byteArray.length; i++){
String subStr = str.substring(2 * i, 2 * i + 2);
byteArray[i] = ((byte)Integer.parseInt(subStr, 16));
}
return byteArray;
}
}