进行 des 加密
package common;
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 DesUtils {
private static final String ENCODE = "UTF-8";
private static final String KEY = "XXX";
public String encrypt(String data) throws Exception {
byte[] bytes = encrypt(data.getBytes(ENCODE), KEY.getBytes(ENCODE));
String string = new BASE64Encoder().encode(bytes);
return string;
}
private byte[] encrypt(byte[] data, byte[] key) throws Exception {
SecureRandom secureRandom = new SecureRandom();
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);
return cipher.doFinal(data);
}
public String decrypt(String data) throws Exception {
if (data == null) {
return null;
}
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] bytes = base64Decoder.decodeBuffer(data);
byte[] bytes1 = encrypt(bytes, KEY.getBytes(ENCODE));
return new String(bytes1, ENCODE);
}
}