package com.esailcar.finance.shenzhou.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
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;
public class SecretDigest {
private final static String MD5="MD5";
private final static String DES="DES";
private final static String ENCODE="UTF-8";
private final static String KEY="asdf1234";
//MD5加密
public static String encodeByMD5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest md5=MessageDigest.getInstance(MD5);
StringBuffer md5buffer=new StringBuffer();
md5.update(str.getBytes("UTF-8"));
byte[] md5bytes=md5.digest();
String hexString=null;
for(byte md5byte : md5bytes)
{
hexString=Integer.toHexString(0xff&md5byte);
if(hexString.length()==1)
{
md5buffer.append("0").append(hexString);
}
else
{
md5buffer.append(hexString);
}
}
return md5buffer.toString();
}
/**
* DES加密
* @param str
* @return
* @throws Exception
*/
public static String encodeByDES(String str)throws Exception
{
byte[] data=str.getBytes(ENCODE);
byte[] key=KEY.getBytes(ENCODE);
SecureRandom sr = new SecureRandom();
// 通过key创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建SecretKeyFactory,把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用securekey初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
//BASE64编码
String message=new BASE64Encoder().encode(cipher.doFinal(data));
return message;
}
/**
* DES解密
* @param str
* @return
* @throws Exception
*/
public static String decodeByDES(String str)throws Exception
{
if (str == null)
return null;
//BASE64解码
BASE64Decoder decoder = new BASE64Decoder();
byte[] data=decoder.decodeBuffer(str);
byte[] key=KEY.getBytes(ENCODE);
SecureRandom sr = new SecureRandom();
// 通过key创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建SecretKeyFactory,把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用securekey初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return new String(cipher.doFinal(data), ENCODE);
}
}