All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.suyeer.basic.util.EncryptUtil Maven / Gradle / Ivy

There is a newer version: 6.0.1
Show newest version
package com.suyeer.basic.util;

import org.apache.http.Consts;
import org.apache.log4j.Logger;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author jun 2018/10/19
 */
public class EncryptUtil {
    private static Logger logger = Logger.getLogger(EncryptUtil.class);

    public static String sha1(String dec) {
        return sha1(dec, Consts.UTF_8);
    }

    public static String sha1(String dec, Charset charset) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(dec.getBytes(charset));
            byte[] messageDigest = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            LogUtil.error("SHA1加密异常!", e);
            return null;
        }
    }

    public static String md5(String dec) {
        return md5(dec, Consts.UTF_8);
    }

    public static String md5(String dec, Charset charset) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = dec.getBytes(charset);
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            LogUtil.error("MD5加密异常!", e);
            return null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy