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 TripleDESUtil {
/**
* 生成密钥
* @return
* @throws Exception
*/
public static byte[] initKey() throws Exception{
// KeyGenerator 密钥生成器
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
// 初始化密钥生成器
keygen.init(168);
// 生成密钥
SecretKey secretKey = keygen.generateKey();
return secretKey.getEncoded();
}

/**
* 3DES 加密
* @param data
* @param key
* @return
* @throws Exception
* @throws NoSuchAlgorithmException
*/
public static byte[] encrype(byte[] data,byte[] key) throws Exception{
// 恢复密钥
SecretKey secretKey = new SecretKeySpec(key, "DESede");
// Cipher 完成加密解密工作
Cipher cipher = Cipher.getInstance("DESede");
// 根据密钥,对Cipher初始化
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密/解密
byte[] cipherByte = cipher.doFinal(data);
return cipherByte;
}

/**
* 3DES 解密
* @param data
* @param key
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
*/
public static byte[] decrype(byte[] data,byte[] key) throws Exception{
SecretKey secretKey = new SecretKeySpec(key, "DESede");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] planByte = cipher.doFinal(data);
return planByte;
}
}