1、实例
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
public class DESCoder {
public static final String ALGORITHM = "DES";
/**
* DES解密
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
try{
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
return cipher.doFinal(data);
}catch(Throwable e){
e.printStackTrace();
}
return null;
}
/**
* DES加密
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
try{
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance(ALGORITHM);
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//现在,获取数据并加密
//正式执行加密操作
return cipher.doFinal(data);
}catch(Throwable e){
e.printStackTrace();
}
return null;
}
/**
* 利用Base64对生成秘钥
*/
public static String initKey(String seed) throws Exception {
String initKey = null;
if (seed != null) {
initKey = encryptBASE64(seed.getBytes());;
} else {
initKey = encryptBASE64("abc123".getBytes());
}
return initKey;
}
/**
* BASE64解密
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* BASE64加密
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
}
/**
* 测试类
*/
import org.junit.Test;
public class DESCoderTest {
@Test
public void test() throws Exception {
//String inputStr = "卖家代充123abc";
String inputStr = "鄢间";
System.err.println("原文:\t" + inputStr);
//生成秘钥
String key = DESCoder.initKey("abc123");
System.err.println("密钥:\t" + key);
//加密
byte[] inputData = inputStr.getBytes();
inputData = DESCoder.encrypt(inputData, key);
System.err.println("加密后:\t" + inputData);
//解密
byte[] outputData = DESCoder.decrypt(inputData, key);
String outputStr = new String(outputData);
System.err.println("解密后:\t" + outputStr);
//验证
Boolean isEquals = assertEquals(inputStr, outputStr);
System.out.println(isEquals);
}
public Boolean assertEquals(String inPut, String outPut){
if(inPut.equals(outPut)){
return true;
}
return false;
}
}