import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
ClassName: EncryptUtil
@Description: 加密工具类 1.将byte[]转为各种进制的字符串 2.base 64 encode 3.base 64 decode
4.获取byte[]的md5值 5.获取字符串md5值 6.结合base64实现md5加密 7.AES加密
8.AES加密为base 64 code 9.AES解密 10.将base 64 code AES解密
@author JornTang
@email [email protected]
-
@date 2017年8月23日
*/
public class EncryptUtil {public static String encodePassword(String password) throws UnsupportedEncodingException {
if (StringUtils.isEmpty(password)) {
return password;
}
return getMD5(password.getBytes("utf-8"));
}public static String getMD5(byte[] source) {
String s = null;
char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
'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(); // MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
s = new String(str); // 换后的结果转换为字符串} catch (Exception e) { e.printStackTrace(); } return s;
}
public final static String MD5(String inputStr) {
// 用于加密的字符
char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
// 使用utf-8字符集将此 String 编码为 byte序列,并将结果存储到一个新的 byte数组中
byte[] btInput = inputStr.getBytes("utf-8");// 信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要 mdInst.update(btInput); // 摘要更新之后,通过调用digest()执行哈希计算,获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { // i = 0 byte byte0 = md[i]; // 95 str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5 str[k++] = md5String[byte0 & 0xf]; // F } // 返回经过加密后的字符串 return new String(str); } catch (Exception e) { return null; }
}
public static String encryption(String plain) throws UnsupportedEncodingException {
String re_md5 = new String();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plain.getBytes("utf-8"));
byte b[] = md.digest();int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } re_md5 = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return re_md5;
}
public static String getMD5(String message) {
String md5 = "";
try {
// Create a MD5 instance
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageByte = message.getBytes("UTF-8");
// get md5 byte array
byte[] md5Byte = md.digest(messageByte);
// switch to Hex
md5 = bytesToHex(md5Byte);
} catch (Exception e) {
e.printStackTrace();
}
return md5;
}/**
- @param bytes
- @return
*/
public static String bytesToHex(byte[] bytes) {
StringBuffer hexStr = new StringBuffer();
int num;
for (int i = 0; i < bytes.length; i++) {
num = bytes[i];
if (num < 0) {
num += 256;
}
if (num < 16) {
hexStr.append("0");
}
hexStr.append(Integer.toHexString(num));
}
return hexStr.toString().toUpperCase();
}
/**
- 将byte[]转为各种进制的字符串
- @param bytes
byte[]
- @param radix
可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制
- @return 转换后的字符串
*/
public static String binary(byte[] bytes, int radix) {
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
}
/**
- base 64 encode
- @param bytes
待编码的byte[]
- @return 编码后的base 64 code
*/
public static String base64Encode(byte[] bytes) {
return new BASE64Encoder().encode(bytes);
}
/**
- base 64 decode
- @param base64Code
待解码的base 64 code
- @return 解码后的byte[]
- @throws Exception
*/
public static byte[] base64Decode(String base64Code) throws Exception {
return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
}
/**
- 获取byte[]的md5值
- @param bytes
byte[]
- @return md5
- @throws Exception
*/
public static byte[] md5(byte[] bytes) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
return md.digest();
}
/**
- 获取字符串md5值
- @param msg
- @return md5
- @throws Exception
*/
public static byte[] md5(String msg) throws Exception {
return StringUtils.isEmpty(msg) ? null : md5(msg.getBytes());
}
/**
- 结合base64实现md5加密
- @param msg
待加密字符串
- @return 获取md5后转为base64
- @throws Exception
*/
public static String md5Encrypt(String msg) throws Exception {
return StringUtils.isEmpty(msg) ? null : base64Encode(md5(msg));
}
/**
AES加密
@param content
待加密的内容
@param encryptKey
加密密钥
@return 加密后的byte[]
-
@throws Exception
*/
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encryptKey.getBytes());
kgen.init(128, random);Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));return cipher.doFinal(content.getBytes("utf-8"));
}
/**
- AES加密为base 64 code
- @param content
待加密的内容
- @param encryptKey
加密密钥
- @return 加密后的base 64 code
- @throws Exception
*/
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
/**
AES解密
@param encryptBytes
待解密的byte[]
@param decryptKey
解密密钥
@return 解密后的String
-
@throws Exception
*/
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(decryptKey.getBytes());
kgen.init(128, random);Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);return new String(decryptBytes);
}
/**
- 将base 64 code AES解密
- @param encryptStr
待解密的base 64 code
- @param decryptKey
解密密钥
- @return 解密后的string
- @throws Exception
*/
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
/**
- 随机生成秘钥
*/
public static String getKey() {
try {
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
// 要生成多少位,只需要修改这里即可128, 192或256
SecretKey sk = kg.generateKey();
byte[] b = sk.getEncoded();
String s = byteToHexString(b);
System.out.println(s);
System.out.println("十六进制密钥长度为" + s.length());
System.out.println("二进制密钥的长度为" + s.length() * 4);
return s;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println("没有此算法。");
}
return null;
}
/**
- 使用指定的字符串生成秘钥
*/
public static String getKeyByPass(String pass) {
// 生成秘钥
try {
KeyGenerator kg = KeyGenerator.getInstance("AES");
// kg.init(128);//要生成多少位,只需要修改这里即可128, 192或256
// SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以生成的秘钥就一样。
SecretKey sk = kg.generateKey();
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(pass.getBytes());
kg.init(128, random);
byte[] b = sk.getEncoded();
String s = byteToHexString(b);
return s;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println("没有此算法。");
}
return null;
}
/**
- byte数组转化为16进制字符串
- @param bytes
- @return
*/
public static String byteToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String strHex = Integer.toHexString(bytes[i]);
if (strHex.length() > 3) {
sb.append(strHex.substring(6));
} else {
if (strHex.length() < 2) {
sb.append("0" + strHex);
} else {
sb.append(strHex);
}
}
}
return sb.toString();
}
// 得到随机字符
public static String randomStr(int n) {
// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
String str1 = "123456789012345678901234567890";
String str2 = "";
int len = str1.length() - 1;
double r;
for (int i = 0; i < n; i++) {
r = (Math.random()) * len;
str2 = str2 + str1.charAt((int) r);
}
return str2;
}// 得到随机密码
public static String randomForPwd(int n) {
String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
String str2 = "";
int len = str1.length() - 1;
double r;
for (int i = 0; i < n; i++) {
r = (Math.random()) * len;
str2 = str2 + str1.charAt((int) r);
}
return str2;
}/**
-
支持前后端加解密
*/
public static String encrypt(String encryContent, String encryKey) throws Exception {
try {
String data = encryContent;
String key = encryKey;
String iv = encryKey;Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return new sun.misc.BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** -
支持前后端加解密
*/
public static String decryEncrypt(String decryContent, String decryKey) throws Exception {
try
{
String data = decryContent;
String key = decryKey;
String iv = decryKey;byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String sss(String myString){
String newString=null;
Pattern CRLF = Pattern.compile("(\r\n|\r|\n|\n\r)");
Matcher m = CRLF.matcher(myString);
if (m.find()) {
newString = m.replaceAll("");
}
return newString;
}
/** @param args
-
@throws Exception
/
public static void main(String[] args) throws Exception {
/- String x = SeqUtil.getUUID(); System.err.println("加密内容:" +
- "18-1D-EA-A2-DC-F3"); //String y = aesEncrypt(x,
- "b8d7b4820efb517e460c925f436a60f6");
- System.err.println(getMD5("18-1D-EA-A2-DC-F3")); //System.err.println("解密后:"
-
- aesDecrypt(y, "b8d7b4820efb517e460c925f436a60f6")); // String
- newStr=sss(aaa); // System.out.println(newStr);
*/ String x = "00-FF-9A-6C-60-B8";
String md5 = EncryptUtil.getMD5(x);
System.err.println(md5);
}
}
作者:云软科技-档案管理系统 JornTang (微信同号)
本篇文章由一文多发平台ArtiPub自动发布