com.gitee.fufu669.utils.CacheDesUtil Maven / Gradle / Ivy
package com.gitee.fufu669.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
@SuppressWarnings({"restriction"})
/** @author wangfupeng */
public class CacheDesUtil {
public static final Logger logger = LoggerFactory.getLogger(CacheDesUtil.class);
private byte[] desKey;
public CacheDesUtil(String desKey) {
this.desKey = desKey.getBytes();
}
public static String base64Encode(byte[] s) {
if (s == null) {
return null;
}
BASE64Encoder b = new BASE64Encoder();
return b.encode(s);
}
public static byte[] base64Decode(String s) throws IOException {
if (s == null) {
return null;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(s);
return b;
}
public byte[] desEncrypt(byte[] plainText) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
byte data[] = plainText;
byte encryptedData[] = cipher.doFinal(data);
return encryptedData;
}
public byte[] desDecrypt(byte[] encryptText) throws Exception {
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;
DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key, sr);
byte encryptedData[] = encryptText;
byte decryptedData[] = cipher.doFinal(encryptedData);
return decryptedData;
}
public String encrypt(String input) throws Exception {
return base64Encode(desEncrypt(input.getBytes()));
}
public String decrypt(String input) throws Exception {
byte[] result = base64Decode(input);
return new String(desDecrypt(result));
}
}