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

io.afu.utils.encryption.Md5Encryption Maven / Gradle / Ivy

There is a newer version: 0.0.55-RELEASE
Show newest version
package io.afu.utils.encryption;

import io.afu.utils.common.constant.CodeConstant;
import io.afu.utils.common.constant.ConstantEnum;
import io.afu.utils.common.constant.MsgConstant;
import io.afu.utils.exception.BaseException;
import io.afu.utils.string.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

public class Md5Encryption {


    /**
     * 计算字符串的Md5值
     * @param str 需要md5加密的字符串
     * @return String
     * @throws BaseException 加密时出错抛出的错误
     */
    public static String md5(String str) throws BaseException{

        try{
            StringBuffer hexString = new StringBuffer();
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            byte[] hash = messageDigest.digest();
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
            return hexString.toString();
        }catch (Exception e){
            throw new BaseException(e);
        }
    }

    /**
     * 计算文件的md5值
     * @param file 需要计算md5值的文件
     * @return String 文件md5值
     * @throws BaseException 计算时出错抛出的错误
     */
    public static String md5(File file) throws BaseException {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            @SuppressWarnings("resource")
            FileInputStream fis = new FileInputStream(file);
            byte[] arr = new byte[1024 * 8];
            int len = 0;
            while ((len = fis.read(arr)) != -1) {
                md5.update(arr, 0, len);
            }
            return EncryptCommon.byteArrayToHex(md5.digest()).toLowerCase();
        }catch (Exception e){
            throw new BaseException(e);
        }
    }

//    /**
//     * '将byte转换为16进制
//     * @param byteArray
//     * @return
//     */
//    public static String byteArrayToHex(byte[] byteArray) {
//        // 首先初始化一个字符数组,用来存放每个16进制字符
//        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
//        // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
//        char[] resultCharArray = new char[byteArray.length * 2];
//        // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
//        int index = 0;
//        for (byte b : byteArray) {
//            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
//            resultCharArray[index++] = hexDigits[b & 0xf];
//        }
//        // 字符数组组合成字符串返回
//        return new String(resultCharArray);
//    }

    /**
     * 通过随机值加密密码
     * @param pwd 需要加密的密码
     * @return String
     * @throws BaseException 加密时出错抛出的错误
     */
    public static String encryptPwd(String pwd) throws BaseException {
        try {

            String salt = StringUtils.randStr(4);
            String strToEncrypt = pwd + salt;
            String encryptedStr = md5(strToEncrypt);
            return encryptedStr+salt;
        }catch (Exception e){
            throw new BaseException(e);
        }
    }

    /**
     * 通过字符串和盐值加密密码
     * @param pwd 需要加密的密码
     * @param salt 加入的盐值
     * @return String
     * @throws BaseException 加密出错时抛出的错误
     */
    public static String encryptPwd(String pwd,String salt) throws BaseException {
        try {
            String strToEncrypt = pwd + salt;
            String encryptedStr = md5(strToEncrypt);
            return encryptedStr + salt;
        }catch (Exception e){
            throw new BaseException(e);
        }
    }

    /**
     * 比对密码和加密后的密码是否是相同的密码
     * @param pwd 需要比对的密码
     * @param encryptedPwd 已经加密的密码
     * @return Boolean
     * @throws BaseException 比对加密出错时抛出的错误
     */
    public static boolean comparePwd(String pwd,String encryptedPwd) throws BaseException {
        if (pwd == null||encryptedPwd == null){
            throw new BaseException();
        }
        try {
            String salt = encryptedPwd.substring(encryptedPwd.length()-4,encryptedPwd.length());
            System.out.println("salt is "+salt);
            String newEncryptPwd = encryptPwd(pwd,salt);
            System.out.println(newEncryptPwd);
            if (newEncryptPwd.equals(encryptedPwd)){
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            throw new BaseException(ConstantEnum.PARAM_ERROR);
        }
    }







}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy