===================使用DES进行加密和解密============================
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.security.SecureRandom;
/**
* 功能: DES加密
*/
private String encrypt(String key, String source){
String algorithm = "DES";
byte [] cipherByte = null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecureRandom sr = new SecureRandom();
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher c1 = Cipher.getInstance(algorithm);
c1.init(Cipher.ENCRYPT_MODE, securekey, sr);
cipherByte = c1.doFinal(source.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder base64encoder = new BASE64Encoder();
String encode=base64encoder.encode(cipherByte);
return encode;
}
/**
* 功能: DES解密
* @param key
* @param source
* @return
*/
private String decrypt(String key, String source){
String algorithm = "DES";
SecureRandom sr = new SecureRandom();
String result = null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encodeByte = base64decoder.decodeBuffer(source);
byte[] cipherByte = cipher.doFinal(encodeByte);
result = new String(cipherByte, "GBK");
} catch (Exception e){
e.printStackTrace();
}
return result;
}