import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.hash.Hashing;
/**
* 加密工具类
*/
public class EncryptUtils {
private static final Logger logger = LoggerFactory.getLogger(EncryptUtils.class);
private static String key = null;
public EncryptUtils(String key) {
this.key = key;
}
/** ========================================== md5加密 ==================================================== */
public static String md5(String input) {
return DigestUtils.md5Hex(input.getBytes());
}
public static String md5(String input, String key) {
return DigestUtils.md5Hex(new StringBuilder().append(input).append(key).toString().getBytes());
}
/**
* 对字符串进行MD5进行加密处理
* @param msg 待加密的字符串
* @return 加密后字符串
*/
public static String encryptMD5(String msg){
return encrypt(msg, null);
}
/**
* 基本加密处理
* @param msg
* @param type
* @return
*/
private static String encrypt(String msg, String type){
MessageDigest md;
StringBuilder password = new StringBuilder();
try {
md = MessageDigest.getInstance("MD5");
if(StringUtils.isNotBlank(type)){
md.update(type.getBytes());
}else {
md.update(msg.getBytes());
}
byte[] bytes = md.digest();
for (int i = 0; i < bytes.length; i++) {
String param = Integer.toString((bytes[i] & 0xff) + 0x100, 16);
password.append(param.substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return password.toString();
}
/**
* MD5加密
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptMD5(byte[] data) throws Exception {
MessageDigest md5 = MessageDigest.getInstance(AlgorithmDefine.ALGORITHM_MD5);
md5.update(data);
return md5.digest();
}
/**
* 生成md5校验码
*
* @param srcContent 需要加密的数据
* @return 加密后的md5校验码。出错则返回null。
*/
public static String makeMd5Sum(byte[] srcContent) {
if (srcContent == null){
return null;
}
String strDes = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(srcContent);
strDes = SecurityUtil.bytes2Hex(md5.digest()); // to HexString
} catch (NoSuchAlgorithmException e) {
return null;
}
return strDes;
}
/**
* 适用于上G大的文件
*
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
*/
@SuppressWarnings("resource")
public static String getFileMD5String(File file) throws IOException, NoSuchAlgorithmException {
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
messagedigest.update(byteBuffer);
return bufferToHex(messagedigest.digest());
}
public static String getMD5String(String s) throws NoSuchAlgorithmException {
String result = null;
try {
result = getMD5String(s.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
public static String getMD5String(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
messagedigest.update(bytes);
return bufferToHex(messagedigest.digest());
}
public static String computeContentMD5Header(InputStream inputStream) {
// Consume the stream to compute the MD5 as a side effect.
DigestInputStream s;
try {
s = new DigestInputStream(inputStream, MessageDigest.getInstance("MD5"));
// drain the buffer, as the digest is computed as a side-effect
byte[] buffer = new byte[8192];
while (s.read(buffer) > 0)
;
return new String(Base64.encodeBase64(s.getMessageDigest().digest()),
"UTF-8");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** ========================================== SHA加密 ==================================================== */
/**
* SHA(Secure Hash Algorithm,安全散列算法)是消息摘要算法的一种,被广泛认可的MD5算法的继任者。
* SHA算法家族目前共有SHA-0、SHA-1、SHA-224、SHA-256、SHA-384和SHA-512五种算法,
* 通常将后四种算法并称为SHA-2算法
* @param msg
* @return
*/
public static String encryptSHA(String msg) {
String salt = getSaltSHA1();
StringBuilder sb = new StringBuilder();
try{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(salt.getBytes());
byte[] bytes = md.digest(msg.getBytes());
for(int i=0; i< bytes.length ;i++){
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
}catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
/**
* [list]
* [*]SHA-1 (Simplest one – 160 bits Hash)
* [*]SHA-256 (Stronger than SHA-1 – 256 bits Hash)
* [*]HA-384 (Stronger than SHA-256 – 384 bits Hash)
* [*]SHA-512 (Stronger than SHA-384 – 512 bits Hash)
* [/list]
* @return
*/
private static String getSaltSHA1(){
SecureRandom sr;
byte[] salt = new byte[16];
try {
sr = SecureRandom.getInstance("SHA1PRNG");
sr.nextBytes(salt);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return salt.toString();
}
/**
* SHA加密
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptSHA(byte[] data) throws Exception {
MessageDigest sha = MessageDigest.getInstance(AlgorithmDefine.ALGORITHM_SHA1);
sha.update(data);
return sha.digest();
}
public static String sha(String input) {
return DigestUtils.sha1Hex(input.getBytes());
}
public static String sha256(String input) {
return DigestUtils.sha256Hex(input.getBytes());
}
public static byte[] encodeHmacSHA256(byte[] data, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), AlgorithmDefine.ALGORITHM_HmacSHA);
// 实例化Mac
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
//初始化mac
mac.init(secretKey);
//执行消息摘要
byte[] digest = mac.doFinal(data);
return digest;
}
public static String sha384(String input) {
return DigestUtils.sha384Hex(input.getBytes());
}
public static String sha512(String input) {
return DigestUtils.sha512Hex(input.getBytes());
}
/**
* 进行MD5加密
*/
public static String passwordMd5(String password) {
try {
return Hashing.sha256().hashString(password, Charset.forName("utf-8")).toString().toUpperCase();
} catch (Exception e) {
logger.error("进行MD5加密发生异常.", e);
}
return null;
}
/** ========================================== BASE64加密 ==================================================== */
public static String base64Encode(String input) {
return Base64.encodeBase64String(input.getBytes()).trim();
}
/**
* BASE64加密
* <p>
* 将二进制内容编码为base64字符串
*
* @param srcContent 需要编码的数据
* @return String 编码结果。如果参数为null,则返回null。
*/
public static String encodeBase64(byte[] srcContent) {
if (srcContent == null) {
return null;
}
String str = new String(new Base64().encode(srcContent));
if (str.contains("\r\n")) {
str = str.replace("\r\n", "");
}
return str;
}
/*public static String encode(String input) {
long millis = System.currentTimeMillis();
input = base64Encode(new StringBuilder().append(input).append(millis).toString());
byte[] bytes = input.getBytes();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
String s = Integer.toHexString(bytes[i] + 18);
sb.append(new StringBuilder().append(s.charAt(1)).append("").append(s.charAt(0)).toString());
}
return SecurityUtil.reverse(sb.toString());
}*/
/** ========================================== AES加密 ==================================================== */
public static String aesEencode(String content) throws Exception {
if (StringUtils.isEmpty(content)) {
return content;
}
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), AlgorithmDefine.ALGORITHM_AES);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(1, keySpec);
return Base64.encodeBase64String(cipher.doFinal(content.getBytes()));
}
public static String aesDecode(String content) throws Exception {
if (StringUtils.isEmpty(content)) {
return content;
}
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), AlgorithmDefine.ALGORITHM_AES);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(2, keySpec);
return new String(cipher.doFinal(Base64.decodeBase64(content)));
}
/** ========================================== DES加密 ==================================================== */
/**
* DES加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptDES(byte[] data, String key) throws Exception {
Key k = SecurityUtil.toKey(DecryptUtils.decryptBASE64(key));
Cipher cipher = Cipher.getInstance(AlgorithmDefine.ALGORITHM_DES);
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/** ========================================== Hex加密 ==================================================== */
private static String bufferToHex(byte bytes[]) {
return bufferToHex(bytes, 0, bytes.length);
}
private static String bufferToHex(byte bytes[], int m, int n) {
StringBuffer stringbuffer = new StringBuffer(2 * n);
int k = m + n;
for (int l = m; l < k; l++) {
appendHexPair(bytes[l], stringbuffer);
}
return stringbuffer.toString();
}
private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
/**
* 默认的密码字符串组合,apache校验下载的文件的正确性用的就是默认的这个组合
*/
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char c0 = hexDigits[(bt & 0xf0) >> 4];
char c1 = hexDigits[bt & 0xf];
stringbuffer.append(c0);
stringbuffer.append(c1);
}
/**
* 盐值的原理非常简单,就是先把密码和盐值指定的内容合并在一起,再使用md5对合并后的内容进行演算,
* 这样一来,就算密码是一个很常见的字符串,再加上用户名,最后算出来的md5值就没那么容易猜出来了。
* 因为攻击者不知道盐值的值,也很难反算出密码原文。
* @param msg
* @return
*/
public static String encryptSalt(String msg) {
String salt = "";
return encrypt(msg, salt);
}
/**
* 先把密码和盐值指定的内容合并在一起,再使用sha1对合并后的内容进行演算,
* @return
*/
private static String getSalt(){
SecureRandom sr;
byte[] salt = new byte[16];
try {
sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
sr.nextBytes(salt);
} catch (Exception e) {
e.printStackTrace();
}
return salt.toString();
}
public static void main(String[] args) throws Exception {
String content = "123";
String password = "tdwACw!#3321!CG";
System.out.println("加密前:" + content);
byte[] bytes = encryptDES(content.getBytes(), password);
System.out.println("加密后:" + new String(bytes,"utf-8"));
}
}
import com.google.common.hash.Hashing;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.*;
import java.sql.Date;
/**
* 解密工具类
*/
public class DecryptUtils {
private static final Logger logger = LoggerFactory.getLogger(DecryptUtils.class);
public static String base64Decode(String input) {
return new String(Base64.decodeBase64(input));
}
/**
* BASE64解密
*
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.decodeBase64(key);
}
/**
* 将base64字符串解码为源数据内容
* 与encode互为相逆的过程
*
* @param base64Code base64编码字符串
* @return byte[] 解码结果。如果参数为null或解码失败,则返回null。
*/
public static byte[] decodeBase64(String base64Code) {
if (base64Code == null) {
return null;
}
return Base64.decodeBase64(base64Code);
}
/**
* DES解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptDES(byte[] data, String key) throws Exception {
Key k = SecurityUtil.toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(AlgorithmDefine.ALGORITHM_DES);
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
/*public static String[] decode(String input) {
try {
if (input.length() % 2 != 0) {
return null;
}
input = SecurityUtil.reverse(input);
byte[] bytes = new byte[input.length() / 2];
for (int i = 0; i <= input.length() - 2; i += 2) {
String hexString = new StringBuilder().append(input.substring(i + 1, i + 2))
.append(input.substring(i, i + 1)).toString();
if (!(hexString.matches("[0-9a-fA-F]+")))
return null;
bytes[(i / 2)] = (byte) (Integer.parseInt(hexString, 16) - 18);
}
String s = new String(bytes);
s = base64Decode(s);
String s1 = s.substring(0, "hello".length());
String s3 = s.substring(s.length() - 13);
if ((!(s1.equals("hello"))) || (!(s3.matches("\\d+"))))
return null;
return new String[]{s.substring("hello".length(), s.length() - 13), s3};
} catch (Exception e) {
}
return null;
}*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len; ) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
}
文章永久链接:https://tech.souyunku.com/25024