一个能进行Base64加密、Base64解密、MD5加密、DES加密、DES解密的工具类(需要sun.misc.BASE64Decoder.jar、Gson的jar)
package com.linxz.comm.utils;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import com.google.gson.Gson;
import com.linxz.comm.po.Token;
import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
/**
* 描述:
* 作者:Linxz
* 邮箱:lin_xiao_zhang@163.com
* 时间: 2017年3月24日 上午11:48:31
* 版本:1.0
*/
public class SecurityUtil {
private static SecurityUtil instance;
private SecurityUtil() throws Exception {
};
synchronized public static SecurityUtil getInstance() throws Exception {
if (instance == null) {
instance = new SecurityUtil();
}
return instance;
}
/** Base64加密 */
public static String getBase64(String s) {
if (s == null)
return null;
BASE64Encoder base64Encoder = new BASE64Encoder();
String b = base64Encoder.encode(s.getBytes());
return b;
}
/** Base64解密 */
public static String getFromBASE64(String s) {
if (s == null)
return null;
BASE64Decoder base64Encoder = new BASE64Decoder();
byte[] b = null;
try {
b = base64Encoder.decodeBuffer(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new String(b);
}
/** MD5加密 */
public static String md5(String string) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] bytes = string.getBytes();
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(bytes);
byte[] updateBytes = messageDigest.digest();
int len = updateBytes.length;
char myChar[] = new char[len * 2];
int k = 0;
for (int i = 0; i < len; i++) {
byte byte0 = updateBytes[i];
myChar[k++] = hexDigits[byte0 >>> 4 & 0x0f];
myChar[k++] = hexDigits[byte0 & 0x0f];
}
return new String(myChar);
} catch (Exception e) {
return null;
}
}
// des加密
/** 加密口令 */
private static final String DES_KEY = "Lcuixian";
/**
* 加密
*
* @param datasource
* byte[]
* @param password
* String
* @return byte[]
*/
public static String encrypt(byte[] datasource, String password) {
try {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
// 现在,获取数据并加密
// 正式执行加密操作
return byteArr2HexStr(cipher.doFinal(datasource));
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
* @param src
* byte[]
* @param password
* String
* @return byte[]
* @throws Exception
*/
public static byte[] decrypt(byte[] src, String password) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
// 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
return cipher.doFinal(src);
}
/**
* 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[]
* hexStr2ByteArr(String strIn) 互为可逆的转换过程
*
*
* @param arrB
* 需要转换的byte数组
*
* @return 转换后的字符串
* @throws Exception
* 本方法不处理任何异常,所有异常全部抛出
*/
private static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
/**
* 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB)
* 互为可逆的转换过程
*
*
* @param strIn
* 需要转换的字符串
* @return 转换后的byte数组
*
* @throws Exception
* 本方法不处理任何异常,所有异常全部抛出
*/
private static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
// 随机生成密钥
private static String getKey() throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 为我们选择的DES算法生成一个KeyGenerator对象
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(sr);
// 生成密匙
SecretKey key = kg.generateKey();
// 获取密匙数据
byte rawKeyData[] = key.getEncoded();
// return new String(rawKeyData);
return byteArr2HexStr(rawKeyData);
}
/**
* 加密指定字符串
*
* @param content:加密内容
*
*/
public static String getDES_Encrypt(String content) throws Exception {
content = content + "`" + getCharAndNumr(3);
String result = encrypt(content.getBytes("UTF8"), DES_KEY);
return result;
}
/**
* 解密指定字符串
*
* @param
*
*/
public static String getDES_dEncrypt(String content) {
// 直接将如上内容解密
String result = null;
try {
byte[] decryResult = decrypt(hexStr2ByteArr(content), DES_KEY);
result = new String(decryResult, "UTF8");
} catch (Exception e1) {
e1.printStackTrace();
}
if (!StringUtils.isEmpty(result)) {
return result.split("`")[0];
} else {
return result;
}
}
/**
* java生成随机数字和字母组合
*
* @param length[生成随机数的长度]
* @return
*/
public static String getCharAndNumr(int length) {
String val = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
// 输出字母还是数字
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 字符串
if ("char".equalsIgnoreCase(charOrNum)) {
// 取得大写字母还是小写字母
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (choice + random.nextInt(26));
} else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// Base64加密
Token token = new Token();
token.setUid("2");
token.setTime((new Date()).getTime());
String json = new Gson().toJson(token);
System.out.println("Base64加密");
System.out.println(getBase64(json));
// Base64解密
System.out.println("Base64解密");
System.out.println(getFromBASE64("eyJ1aWQiOiIyIiwidGltZSI6MTQ5MDMzMjg5NDIzMX0="));
// md5加密
System.out.println("md5加密");
System.out.println(md5("1877804110"));
//DES加密
System.out.println("DES加密");
System.out.println(getDES_Encrypt("1877804110"));
//System.out.println("DES解密");
//DES加密没有转Base64,会导致解密失败
//System.out.println(getDES_dEncrypt("0004cfe13f352fde1f2077dde9bcaf22"));
//随机生成10个字母+数字
System.out.println("随机生成10个字母+数字");
System.out.println(getCharAndNumr(10));
}
}
运行结果: