import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.sun.crypto.provider.SunJCE;
public class DesUtil {
private static final Logger logger = Logger.getLogger(DesUtil.class);
private static final String ALGORITHM = "DES";
private KeyGenerator keyGenerator;
private SecretKey secretKey;
private Cipher cipher;
public DesUtil(String key) {
this.init(key);
}
private void init(String key) {
Security.addProvider(new SunJCE());
try {
this.keyGenerator = KeyGenerator.getInstance(ALGORITHM);
this.keyGenerator.init(new SecureRandom(key.getBytes()));
this.secretKey = this.keyGenerator.generateKey();
this.cipher = Cipher.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException e) {
logger.error(e);
} catch (NoSuchPaddingException e) {
logger.error(e);
}
}
/**
* 加密
* @param expreStr
* @return
*/
public String encry(String expreStr) {
byte[] cipByte = null;// 密文数组
byte[] expreByte = null;// 明文数组
String cipStr = ""; // 密文
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
expreByte = expreStr.getBytes("UTF-8");
this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
cipByte = this.cipher.doFinal(expreByte);
cipStr = base64Encoder.encode(cipByte);
} catch (UnsupportedEncodingException e) {
logger.error(e);
} catch (InvalidKeyException e) {
logger.error(e);
} catch (IllegalBlockSizeException e) {
logger.error(e);
} catch (BadPaddingException e) {
logger.error(e);
}
return cipStr;
}
/**
* 解密
* @param cipStr
* @return
*/
public String decry(String cipStr) {
byte[] cipByte = null;// 密文数组
byte[] expreByte = null; // 明文数组
String expreStr = "";// 明文
BASE64Decoder base64Decoder = new BASE64Decoder();
try {
cipByte = base64Decoder.decodeBuffer(cipStr);
this.cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
expreByte = this.cipher.doFinal(cipByte);
expreStr = new String(expreByte, "UTF-8");
} catch (IOException e) {
logger.error(e);
} catch (InvalidKeyException e) {
logger.error(e);
} catch (IllegalBlockSizeException e) {
logger.error(e);
} catch (BadPaddingException e) {
logger.error(e);
}
return expreStr;
}
public static void main(String[] args) {
String pwd = "12345 6";
System.out.println("加密前:" + pwd);
DesUtil desUtil = new DesUtil("abc");
String encStr = desUtil.encry(pwd);
System.out.println("加密后:" + encStr);
String decStr = desUtil.decry(encStr);
System.out.println("解密后:" + decStr);
}
}