package test.util;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class DESUtil {
/**
* 生成密钥
* @return
* @throws Exception
*/
public static byte[] initKey() throws Exception{
// KeyGenerator 密钥生成器
KeyGenerator keygen = KeyGenerator.getInstance("DES");
// 初始化密钥生成器
keygen.init(56);
// 生成密钥
SecretKey secretKey = keygen.generateKey();
return secretKey.getEncoded();
}
/**
* DES 加密
* @param data
* @param key
* @return
* @throws Exception
* @throws NoSuchAlgorithmException
*/
public static byte[] encrype(byte[] data,byte[] key) throws Exception{
// 恢复密钥
SecretKey secretKey = new SecretKeySpec(key, "DES");
// Cipher 完成加密解密工作
Cipher cipher = Cipher.getInstance("DES");
// 根据密钥,对Cipher初始化
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密/解密
byte[] cipherByte = cipher.doFinal(data);
return cipherByte;
}
/**
* DES 解密
* @param data
* @param key
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
*/
public static byte[] decrype(byte[] data,byte[] key) throws Exception{
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] planByte = cipher.doFinal(data);
return planByte;
}
}