Encrypt方式加密
package com.cc.common.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* 功能描述
* 加密常用类
*/
public class EncryptUtil {
// 密钥是16位长度的byte[]进行Base64转换后得到的字符串
public static String key = "LmMGStGtOpF4xNyvYt54EQ==";
/**
* <li>
* 方法名称:encrypt</li> <li>
* 加密方法
* @param xmlStr
* 需要加密的消息字符串
* @return 加密后的字符串
*/
public static String encrypt(String xmlStr) {
byte[] encrypt = null;
try {
// 取需要加密内容的utf-8编码。
encrypt = xmlStr.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 取MD5Hash码,并组合加密数组
byte[] md5Hasn = null;
try {
md5Hasn = EncryptUtil.MD5Hash(encrypt, 0, encrypt.length);
} catch (Exception e) {
e.printStackTrace();
}
// 组合消息体
byte[] totalByte = EncryptUtil.addMD5(md5Hasn, encrypt);
// 取密钥和偏转向量
byte[] key = new byte[8];
byte[] iv = new byte[8];
getKeyIV(EncryptUtil.key, key, iv);
SecretKeySpec deskey = new SecretKeySpec(key, "DES");
IvParameterSpec ivParam = new IvParameterSpec(iv);
// 使用DES算法使用加密消息体
byte[] temp = null;
try {
temp = EncryptUtil.DES_CBC_Encrypt(totalByte, deskey, ivParam);
} catch (Exception e) {
e.printStackTrace();
}
// 使用Base64加密后返回
return new BASE64Encoder().encode(temp);
}
/**
* <li>
* 方法名称:encrypt</li> <li>
* 功能描述:
* 解密方法
* @param xmlStr
* 需要解密的消息字符串
* @return 解密后的字符串
* @throws Exception
*/
public static String decrypt(String xmlStr) throws Exception {
// base64解码
BASE64Decoder decoder = new BASE64Decoder();
byte[] encBuf = null;
try {
encBuf = decoder.decodeBuffer(xmlStr);
} catch (IOException e) {
e.printStackTrace();
}
// 取密钥和偏转向量
byte[] key = new byte[8];
byte[] iv = new byte[8];
getKeyIV(EncryptUtil.key, key, iv);
SecretKeySpec deskey = new SecretKeySpec(key, "DES");
IvParameterSpec ivParam = new IvParameterSpec(iv);
// 使用DES算法解密
byte[] temp = null;
try {
temp = EncryptUtil.DES_CBC_Decrypt(encBuf, deskey, ivParam);
} catch (Exception e) {
e.printStackTrace();
}
// 进行解密后的md5Hash校验
byte[] md5Hash = null;
try {
md5Hash = EncryptUtil.MD5Hash(temp, 16, temp.length - 16);
} catch (Exception e) {
e.printStackTrace();
}
// 进行解密校检
for (int i = 0; i < md5Hash.length; i++) {
if (md5Hash[i] != temp[i]) {
// System.out.println(md5Hash[i] + "MD5校验错误。" + temp[i]);
throw new Exception("MD5校验错误。");
}
}
// 返回解密后的数组,其中前16位MD5Hash码要除去。
return new String(temp, 16, temp.length - 16, "utf-8");
}
public static String decode(String str, String encoding){
String result = null;
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer( str );
if (StringUtils.isEmpty(encoding)) {
encoding = "UTF-8";
}
result = new String(bt, encoding);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* <li>
* 方法名称:TripleDES_CBC_Encrypt</li> <li>
* 功能描述:
* 经过封装的三重DES/CBC加密算法,如果包含中文,请注意编码。
* @param sourceBuf
* 需要加密内容的字节数组。
* @param deskey
* KEY 由24位字节数组通过SecretKeySpec类转换而成。
* @param ivParam
* IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。
* @return 加密后的字节数组
* @throws Exception
*/
public static byte[] TripleDES_CBC_Encrypt(byte[] sourceBuf,
SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
byte[] cipherByte;
// 使用DES对称加密算法的CBC模式加密
Cipher encrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);
cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
// 返回加密后的字节数组
return cipherByte;
}
/**
* <li>
* 方法名称:TripleDES_CBC_Decrypt</li> <li>
* 功能描述:
* 经过封装的三重DES / CBC解密算法
* @param sourceBuf
* 需要解密内容的字节数组
* @param deskey
* KEY 由24位字节数组通过SecretKeySpec类转换而成。
* @param ivParam
* IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。
* @return 解密后的字节数组
* @throws Exception
*/
public static byte[] TripleDES_CBC_Decrypt(byte[] sourceBuf,
SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
byte[] cipherByte;
// 获得Cipher实例,使用CBC模式。
Cipher decrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");
// 初始化加密实例,定义为解密功能,并传入密钥,偏转向量
decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);
cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
// 返回解密后的字节数组
return cipherByte;
}
/**
* <li>
* 方法名称:DES_CBC_Encrypt</li> <li>
* 功能描述:
* 经过封装的DES/CBC加密算法,如果包含中文,请注意编码。
* @param sourceBuf
* 需要加密内容的字节数组。
* @param deskey
* KEY 由8位字节数组通过SecretKeySpec类转换而成。
* @param ivParam
* IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。
* @return 加密后的字节数组
* @throws Exception
*/
public static byte[] DES_CBC_Encrypt(byte[] sourceBuf,
SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
byte[] cipherByte;
// 使用DES对称加密算法的CBC模式加密
Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);
cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
// 返回加密后的字节数组
return cipherByte;
}
/**
* <li>
* 方法名称:DES_CBC_Decrypt</li> <li>
* 功能描述:
* 经过封装的DES/CBC解密算法。
* @param sourceBuf
* 需要解密内容的字节数组
* @param deskey
* KEY 由8位字节数组通过SecretKeySpec类转换而成。
* @param ivParam
* IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。
* @return 解密后的字节数组
* @throws Exception
*/
public static byte[] DES_CBC_Decrypt(byte[] sourceBuf,
SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
byte[] cipherByte;
// 获得Cipher实例,使用CBC模式。
Cipher decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 初始化加密实例,定义为解密功能,并传入密钥,偏转向量
decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);
cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
// 返回解密后的字节数组
return cipherByte;
}
/**
* <li>
* 方法名称:MD5Hash</li> <li>
* 功能描述:
*
* <pre>
* MD5,进行了简单的封装,以适用于加,解密字符串的校验。
* @param buf
* 需要MD5加密字节数组。
* @param offset
* 加密数据起始位置。
* @param length
* 需要加密的数组长度。
* @return
* @throws Exception
*/
public static byte[] MD5Hash(byte[] buf, int offset, int length)
throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(buf, offset, length);
return md.digest();
}
/**
* <li>
* 方法名称:byte2hex</li> <li>
* 功能描述:
* 字节数组转换为二行制表示
* @param inStr
* 需要转换字节数组。
* @return 字节数组的二进制表示。
*/
public static String byte2hex(byte[] inStr) {
String stmp;
StringBuffer out = new StringBuffer(inStr.length * 2);
for (int n = 0; n < inStr.length; n++) {
// 字节做"与"运算,去除高位置字节 11111111
stmp = Integer.toHexString(inStr[n] & 0xFF);
if (stmp.length() == 1) {
// 如果是0至F的单位字符串,则添加0
out.append("0" + stmp);
} else {
out.append(stmp);
}
}
return out.toString();
}
/**
* <li>
* 方法名称:addMD5</li> <li>
* 功能描述:
* <pre>
* MD校验码 组合方法,前16位放MD5Hash码。 把MD5验证码byte[],加密内容byte[]组合的方法。
* @param md5Byte
* 加密内容的MD5Hash字节数组。
* @param bodyByte
* 加密内容字节数组
* @return 组合后的字节数组,比加密内容长16个字节。
*/
public static byte[] addMD5(byte[] md5Byte, byte[] bodyByte) {
int length = bodyByte.length + md5Byte.length;
byte[] resutlByte = new byte[length];
// 前16位放MD5Hash码
for (int i = 0; i < length; i++) {
if (i < md5Byte.length) {
resutlByte[i] = md5Byte[i];
} else {
resutlByte[i] = bodyByte[i - md5Byte.length];
}
}
return resutlByte;
}
/**
* <li>
* 方法名称:getKeyIV</li> <li>
* 功能描述:
* @param encryptKey
* @param key
* @param iv
*/
public static void getKeyIV(String encryptKey, byte[] key, byte[] iv) {
// 密钥Base64解密
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = null;
try {
buf = decoder.decodeBuffer(encryptKey);
} catch (IOException e) {
e.printStackTrace();
}
// 前8位为key
int i;
for (i = 0; i < key.length; i++) {
key[i] = buf[i];
}
// 后8位为iv向量
for (i = 0; i < iv.length; i++) {
iv[i] = buf[i + 8];
}
}
}
MD5加密代码如下
package com.ig.common.util;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
/**
* Created by Terry on 2015/7/16.
* MD5加密工具类
*/
public class MD5Util {
private static final char DIGITS_LOWER[] = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char DIGITS_UPPER[] = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static final String DEFAULT_ENCODING = "UTF8";
private static final String ALGORITH = "MD5";
private static final MessageDigest md = getMessageDigest(ALGORITH);
/**
* MD5(32位的十六进制表示)
*
* @param srcStr
* 源字符串
* @param encode
* 编码方式
* @return
*/
public static String digest(String srcStr, String encode) {
byte[] rstBytes;
try {
rstBytes = md.digest(srcStr.getBytes(encode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return toHex(rstBytes, true);
}
/**
* 默认使用UTF8编码进行解析
*
* @param srcStr
* 源字符串
* @return
*/
public static String digest(String srcStr) {
return digest(srcStr, DEFAULT_ENCODING);
}
/**
* 获取摘要处理实例
*
* @param algorithm
* 摘要的算法
* @return
*/
private static MessageDigest getMessageDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 字节码转十六进制的字符串
*
* @param bytes
* 字节数组
* @param flag
* 大小写标志,true为小写,false为大写
* @return
*/
public static String toHex(byte[] bytes, boolean flag) {
return new String(processBytes2Hex(bytes, flag ? DIGITS_LOWER : DIGITS_UPPER));
}
/**
* 将字节数组转化为十六进制字符串
*
* @param bytes
* 字节数组
* @param digits
* 数字加字母字符数组
* @return
*/
private static char[] processBytes2Hex(byte[] bytes, char[] digits) {
// bytes.length << 1肯定是32,左移1位是因为一个字节是8位二进制,一个十六进制用4位二进制表示
// 当然可以写成l = 32,因为MD5生成的字节数组必定是长度为16的字节数组
int l = bytes.length << 1;
char[] rstChars = new char[l];
int j = 0;
for (int i = 0; i < bytes.length; i++) {
// 得到一个字节中的高四位的值
rstChars[j++] = digits[(0xf0 & bytes[i]) >>> 4];
// 得到一个字节中低四位的值
rstChars[j++] = digits[0x0f & bytes[i]];
}
return rstChars;
}
public static String encode(byte[] source) {
String s = null;
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
s = new String(str);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
public static String getDataByMD5(byte[] source){
String str = null;
//用来将字节转换成16进制表示的字符
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(source);
//MD5的计算结果是一个128位的长整数
byte tmp[] = md.digest();
//用字节表示就是16个字节
char s[] = new char[16*2];
//表示16成16进制需要32个字符
int k = 0;//表示转换结果中对应的字符为止
for (int i = 0; i < 16; i++) {
//从第一个字节开始,对MD5的某一个字节转换成16进制字符的转换
byte byte0 = tmp[i];//取第i个字节
s[k++] = hexDigits[byte0 >>> 4 & 0xf];//去掉字节中高4位的数字转换
//>>>为右逻辑右移,将符号位一起右移
s[k++] = hexDigits[byte0 & 0xf];//取字节中低4位的数字转换
}
//换后的结果转换为字符串
str = new String(s);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static String getMD5(byte[] source){
String MD5String="";
String submitvc=getDataByMD5(MD5String.getBytes());
submitvc=submitvc+getDataByMD5(source);
return getDataByMD5(submitvc.getBytes());
}
public static String getMD5One(byte[] source){
return getDataByMD5(source);
}
private MessageDigest __md5 = null;
private StringBuffer __digestBuffer = null;
public MD5Util()
throws NoSuchAlgorithmException
{
__md5 = MessageDigest.getInstance("MD5");
__digestBuffer = new StringBuffer();
}
public String md5crypt(String s)
{
__digestBuffer.setLength(0);
byte abyte0[] = __md5.digest(s.getBytes());
for(int i = 0; i < abyte0.length; i++)
__digestBuffer.append(toHex(abyte0[i]));
return __digestBuffer.toString();
}
public String toHex(byte one){
String HEX="0123456789ABCDEF";
char[] result=new char[2];
result[0]=HEX.charAt((one & 0xf0) >> 4);
result[1]=HEX.charAt(one & 0x0f);
String mm=new String(result);
return mm;
}
public static String getMD5ofStr(String str){
return getMD5ofStr(str,"utf-8");
}
public static String getMD5ofStr(String str, String encode) {
try{
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(str.getBytes(encode));
byte[] digest = md5.digest();
StringBuffer hexString = new StringBuffer();
String strTemp;
for (int i = 0; i < digest.length; i++) {
// byteVar &
// 0x000000FF的作用是,如果digest[i]是负数,则会清除前面24个零,正的byte整型不受影响。
// (...) | 0xFFFFFF00的作用是,如果digest[i]是正数,则置前24位为一,
// 这样toHexString输出一个小于等于15的byte整型的十六进制时,倒数第二位为零且不会被丢弃,这样可以通过substring方法进行截取最后两位即可。
strTemp = Integer.toHexString(
(digest[i] & 0x000000FF) | 0xFFFFFF00).substring(6);
hexString.append(strTemp);
}
return hexString.toString();
}catch(Exception e){
e.printStackTrace();
return "";
}
}
public static String signByMD5(String sourceData, String key, String charset)
throws Exception {
String data = sourceData + key;
MessageDigest md5 = MessageDigest.getInstance("MD5");
if (StringUtils.isEmpty(charset)) {
charset = "UTF-8";
}
byte[] sign = md5.digest(data.getBytes(charset));
return Bytes2HexString(sign).toUpperCase();
}
/**
* 将byte数组转成十六进制的字符串
*
* @param b
* byte[]
* @return String
*/
public static String Bytes2HexString(byte[] b) {
StringBuffer ret = new StringBuffer(b.length);
String hex = "";
for (int i = 0; i < b.length; i++) {
hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret.append(hex.toUpperCase());
}
return ret.toString();
}
}