DES是典型的对称可逆算法
package com.tools.encrypt;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
*
* @ClassName: DESEncrypt
* @Description:TODO(DES可逆加密,密码可解)
* @author: chenanzhi
* @date: 2015-1-6 下午05:25:44
*
*/
public class DESEncrypt {
public static final String ALGORITHM = "DES";
public static final String KEY = "5566233559955";
private static Key newkey;
private static DESEncrypt edd = null;
private DESEncrypt()
{
getKey(KEY);
}
public static synchronized DESEncrypt getEdd() {
if (edd == null)
{
edd = new DESEncrypt();
}
return edd;
}
/**
* 装换密钥
*/
private void getKey(String strKey)
{
try
{
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
generator.init(new SecureRandom(strKey.getBytes()));
newkey = generator.generateKey();
} catch (Exception e) {
e.printStackTrace();
}
}
private String getEncString(String strMing)
{
byte[] byteMi = (byte[])null;
byte[] byteStr = (byte[])null;
String strMi = "";
BASE64Encoder base64en = new BASE64Encoder();
try {
byteStr = strMing.getBytes("UTF8");
byteMi = getEncCode(byteStr);
strMi = base64en.encode(byteMi);
} catch (Exception e) {
e.printStackTrace();
} finally {
base64en = null;
byteStr = (byte[])null;
byteMi = (byte[])null;
}
return strMi;
}
/**
*
* @Title: getEncrypt
* @Description: TODO(加密方法)
* @param: @param strMing
* @param: @return
* @return: String
* @throws
*/
public String getEncrypt(String strMing)
{
String outstr = getEncString(strMing);
return outstr;
}
private String getDesString(String strMi)
{
BASE64Decoder base64De = new BASE64Decoder();
byte[] byteMing = (byte[])null;
byte[] byteStr = (byte[])null;
String strMing = "";
try {
byteStr = base64De.decodeBuffer(strMi);
byteMing = getDesCode(byteStr);
strMing = new String(byteMing, "UTF8");
} catch (Exception e) {
e.printStackTrace();
} finally {
base64De = null;
byteMing = (byte[])null;
byteStr = (byte[])null;
}
return strMing;
}
/**
*
* @Title: getDecrypt
* @Description: TODO(解密方法)
* @param: @param impStr
* @param: @return
* @return: String
* @throws
*/
public String getDecrypt(String impStr)
{
String outStr = getDesString(impStr);
return outStr;
}
private byte[] getEncCode(byte[] byteS)
{
byte[] byteFina = (byte[])null;
Cipher cipher;
try
{
cipher = Cipher.getInstance("DES");
cipher.init(1, newkey);
byteFina = cipher.doFinal(byteS);
} catch (Exception e) {
e.printStackTrace();
}
return byteFina;
}
private byte[] getDesCode(byte[] byteD)
{
byte[] byteFina = (byte[])null;
Cipher cipher;
try
{
cipher = Cipher.getInstance("DES");
cipher.init(2, newkey);
byteFina = cipher.doFinal(byteD);
} catch (Exception e) {
e.printStackTrace();
}
return byteFina;
}
}