常用的加密编码工具类Base64和MD5

Base64Utils

import com.myblog.utils.StringUtil;

import java.io.*;
import java.util.Base64;

/**
 * @Author: 随风飘的云
 * @Description: Base64工具类,详情请参考:https://www.cnblogs.com/smile361/p/6362075.html
 * @Date: 2022/2/19 12:54
 * @Modified By:
 */
public class Base64Utils {

    // 基线长度
    private static final int BASELENGTH = 128;
    // 外观长度
    private static final int LOOKUPLENGTH = 64;
    // 24位集团
    private static final int TWENTYFOURBITGROUP = 24;
    // 8位
    private static final int EIGHTBIT = 8;
    // 6位
    private static final int SIXTEENBIT = 16;

    private static final int FOURBYTE = 4;

    private static final int SIGN =  -128;

    private static final char PAD = '=';

    // 转换表
    private static byte[] base64Alphabet = new byte[BASELENGTH];

    // 字符对照表
    private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];

    // 文件读取缓冲区大小
    private static final int FILE_SIZE = 1024;

    static {
        // 根据ASCII表初始化整个base64Alphabet对照表,详情请参考:
        // https://baike.baidu.com/item/base64/8545775?fr=aladdin 的转换表
        // 例如ASCII表中90对应(大写)Z,则base64Alphabet[90] = 25,对应于转换表中的(大写)Z
        for (int i = 0; i < BASELENGTH; i++) {
            base64Alphabet[i] = -1;
        }
        for (int i = 'Z'; i >= 'A'; i--) {
            base64Alphabet[i] = (byte)(i - 'A');
        }
        for (int i = 'z'; i >= 'a'; i--) {
            base64Alphabet[i] = (byte)(i - 'a' + 26);
        }
        for (int i = '9'; i >= '0'; i--) {
            base64Alphabet[i] = (byte)(i - '0' + 52);
        }
        base64Alphabet['+'] = 62;
        base64Alphabet['/'] = 63;

        // 初始化所有的base64的转换表
        for (int i = 0; i <= 25; i++) {
            lookUpBase64Alphabet[i] = (char)('A' + i);
        }
        for (int i = 26, j = 0; i <= 51 ; i++, j++) {
            lookUpBase64Alphabet[i] = (char)('a' + j);
        }
        for (int i = 52, j = 0; i <= 61; i++, j++) {
            lookUpBase64Alphabet[i] = (char)('0' + j);
        }
        lookUpBase64Alphabet[62] = '+';
        lookUpBase64Alphabet[63] = '-';
    }


    /**
     * 判断是否为空格
     * @param oct
     * @return
     */
    public static boolean isWhiteSpace(char oct){
        return oct == 0x20 || oct == 0xd || oct == 0xa || oct == 0x9;
    }

    /**
     * 判断是否为等号
     * @param oct
     * @return
     */
    public static boolean isPad(char oct) {
        return oct == PAD;
    }

    /**
     * 判断是否是输入ASCII表的字符
     * @param oct
     * @return
     */
    public static boolean isData(char oct){
        return oct < BASELENGTH && base64Alphabet[oct] != -1;
    }

    public static boolean isBase(String data){
        return isArrayBase64(data.getBytes());
    }

    public static boolean isBase(byte data){
        return data == PAD || base64Alphabet[data] != -1;
    }

    /**
     * 判断是属于base64格式类型的。
     * @param data
     * @return
     */
    public static boolean isArrayBase64(byte[] data){
        int len = data.length;
        if(len == 0){
            return true;
        }
        for (int i = 0; i < len; i++) {
            if(!isBase(data[i])){
                return false;
            }
        }
        return true;
    }



    /**
     * Encodes hex octects into Base64
     * 编码
     * @param binaryData Array containing binaryData
     * @return Encoded Base64 array
     */
    public static String encode(byte[] binaryData)
    {
        if (binaryData == null)
        {
            return null;
        }

        int lengthDataBits = binaryData.length * EIGHTBIT;
        if (lengthDataBits == 0)
        {
            return "";
        }

        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
        char encodedData[] = null;

        encodedData = new char[numberQuartet * 4];

        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

        int encodedIndex = 0;
        int dataIndex = 0;

        for (int i = 0; i < numberTriplets; i++)
        {
            b1 = binaryData[dataIndex++];
            b2 = binaryData[dataIndex++];
            b3 = binaryData[dataIndex++];

            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
        }

        // form integral number of 6-bit groups
        if (fewerThan24bits == EIGHTBIT)
        {
            b1 = binaryData[dataIndex];
            k = (byte) (b1 & 0x03);
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
            encodedData[encodedIndex++] = PAD;
            encodedData[encodedIndex++] = PAD;
        }
        else if (fewerThan24bits == SIXTEENBIT)
        {
            b1 = binaryData[dataIndex];
            b2 = binaryData[dataIndex + 1];
            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
            encodedData[encodedIndex++] = PAD;
        }
        return new String(encodedData);
    }

    /**
     * 解码成功
     * @param str 传入需要解码的str,
     * @param charset 解码后返回的格式
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decode(String str, String charset) throws UnsupportedEncodingException {
        String result = null;
        if(!StringUtil.isEmpty(str)){
            byte[] bytes = decode(str);
            if(bytes != null && bytes.length > 0){
                result = new String(bytes, charset);
            }
        }
        return result;
    }

    /**
     * Decodes Base64 data into octects
     * 解码
     * @param encoded string containing Base64 data
     * @return Array containind decoded data.
     */
    public static byte[] decode(String encoded)
    {
        if (encoded == null)
        {
            return null;
        }

        char[] base64Data = encoded.toCharArray();
        // remove white spaces
        int len = removeWhiteSpace(base64Data);

        if (len % FOURBYTE != 0)
        {
            return null;// should be divisible by four
        }

        int numberQuadruple = (len / FOURBYTE);

        if (numberQuadruple == 0)
        {
            return new byte[0];
        }

        byte decodedData[] = null;
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

        int i = 0;
        int encodedIndex = 0;
        int dataIndex = 0;
        decodedData = new byte[(numberQuadruple) * 3];

        for (; i < numberQuadruple - 1; i++)
        {

            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
                    || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++])))
            {
                return null;
            } // if found "no data" just return null

            b1 = base64Alphabet[d1];
            b2 = base64Alphabet[d2];
            b3 = base64Alphabet[d3];
            b4 = base64Alphabet[d4];

            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
        }

        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])))
        {
            return null;// if found "no data" just return null
        }

        b1 = base64Alphabet[d1];
        b2 = base64Alphabet[d2];

        d3 = base64Data[dataIndex++];
        d4 = base64Data[dataIndex++];
        if (!isData((d3)) || !isData((d4)))
        {// 检测是否为等号
            if (isPad(d3) && isPad(d4))
            {
                if ((b2 & 0xf) != 0)// last 4 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 1];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
                return tmp;
            }
            else if (!isPad(d3) && isPad(d4))
            {
                b3 = base64Alphabet[d3];
                if ((b3 & 0x3) != 0)// last 2 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 2];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
                return tmp;
            }
            else
            {
                return null;
            }
        }
        else
        { // No PAD e.g 3cQl
            b3 = base64Alphabet[d3];
            b4 = base64Alphabet[d4];
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

        }
        return decodedData;
    }

    private static int removeWhiteSpace(char[] data) {
        if (data == null)
        {
            return 0;
        }

        // count characters that's not whitespace
        int newSize = 0;
        int len = data.length;
        for (int i = 0; i < len; i++)
        {
            if (!isWhiteSpace(data[i]))
            {
                data[newSize++] = data[i];
            }
        }
        return newSize;
    }

    /**
     * 文件转换为二进制数组
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public static byte[] fileToByte(String path) throws IOException {
        byte[] data = new byte[0];
        File file = new File(path);
        if(file.exists()){
            FileInputStream inputStream = new FileInputStream(file);
            // 输入缓冲区
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048);
            // 缓冲数组大小
            byte[] cache = new byte[FILE_SIZE];
            int read = 0;
            while ((read = inputStream.read(cache)) != -1){
                // 写入缓冲数组
                outputStream.write(cache, 0, read);
                // 重新刷新缓冲区
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
            data = outputStream.toByteArray();
        }
        return data;
    }

    /**
     * 二进制数组转文件
     * @param bytes
     * @param path
     * @throws IOException
     */
    public static void ByteToFile(byte[] bytes, String path) throws IOException {
        // 文件输入缓冲区
        InputStream inputStream = new ByteArrayInputStream(bytes);
        File file = new File(path);
        // 判断父目录是否存在,不存在则创建文件目录
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        // 创建文件
        file.createNewFile();
        // 输出缓冲区
        OutputStream outputStream = new FileOutputStream(file);
        byte[] cache = new byte[FILE_SIZE];
        int read = 0;
        while ((read = inputStream.read(cache)) != -1){
            outputStream.write(cache, 0, read);
            outputStream.flush();
        }
        inputStream.close();
        outputStream.close();
    }

    /**
     * 文件转String类型的base64数据
     * @param path
     * @return
     * @throws IOException
     */
    public static String encodeFile(String path) throws IOException {
        byte[] data = fileToByte(path);
        return encode(data);
    }

    /**
     * 二进制数据转文件
     * @param path
     * @param base
     * @throws IOException
     */
    public static void decodeFile(String path, String base) throws IOException {
        byte[] base64 = decode(base);
        ByteToFile(base64, path);
    }
}

MD5Utils

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: 随风飘的云
 * @Description: MD5工具类
 * @Date: 2022/2/19 11:26
 * @Modified By:
 */
public class MD5Utils{

    private static Logger logger = LoggerFactory.getLogger(MD5Utils.class);

    private static MessageDigest digest = null;

    // 添加盐值
    private byte[] salt;
    // 加盐的位置,即盐值字符串放在加密字符串中的位置
    private int position;

    /**
     * 默认构造方法
     */
    public MD5Utils(){
        this.salt = null;
        this.position = -1;
    }

    /**
     * 构造方法,初始化盐值,加盐的位置,散列次数
     * @param salt
     * @param position
     */
    public MD5Utils(byte[] salt, int position){
        this.salt = salt;
        this.position = position;
    }

    /**
     * 初始化MessageDigest
     */
    private static void init(){
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.debug("MD5加密日志实现的错误日志 ====>>" + e.getMessage(), e);
        }
    }

    /**
     * 解码,不然会输出乱码
     * @param datas
     * @return
     */
    private static String decodeStr(byte[] ...datas){
        StringBuffer buffer = new StringBuffer();
        // 设置多参数,可以省略
        for (byte[] data: datas) {
            int len = data.length;
            // 进行编码
            for (int i = 0; i < len; i++) {
                int val = ((int) data[i]) & 0xff;
                if(val < 16){
                    buffer.append("0");
                }
                buffer.append(Integer.toHexString(val));
            }
        }
        return new String(buffer);
    }

    /**
     * MD5加密算法,不可逆,可以设置加盐的位置。
     * @param data
     * @return
     */
    public byte[] encode(byte[] data){
        byte[] result = new byte[0];
        String str = "";
        init();
        if(this.position == 0){
            // 加盐在开头,自动忽略空盐值
            result = doDigest(this.salt, data);
        } else if(this.position >= data.length){
            // 加盐在末尾,自动忽略空盐值
            result = doDigest(data, this.salt);
        } else if(this.salt != null && this.salt.length > 0){
            // 加盐在中间
            digest.update(data, 0, this.position);
            digest.update(this.salt);
            digest.update(data, this.position, data.length - this.position);
            result = digest.digest();
        } else if(this.position < 0){
            // 不加盐
            result = doDigest(data);
        }
        str = decodeStr(result);
        return str.getBytes();
    }

    /**
     * 生成摘要
     * @param datas
     * @return
     */
    private static byte[] doDigest(byte[] ...datas){
        for (byte[] data: datas) {
            if(data != null){
                digest.update(data);
            }
        }
        return digest.digest();
    }

}

整合Base64和MD5

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: 随风飘的云
 * @Description: 加密算法工具类
 * @Date: 2022/2/19 10:55
 * @Modified By:
 */
public class SecretUtils {

    private static final Logger log = LoggerFactory.getLogger(SecretUtils.class);

    /**
     * 调用Base64编码
     * @param data
     * @return
     */
    public static String encodeBase64(String data){
        String result = Base64Utils.encode(data.getBytes());
        log.debug("自定义Base64编码加密的32位秘钥的调试日志 ====>>"+ result);
        return result;
    }

    /**
     * 调用MD5加密
     * @param data
     * @return
     */
    public static String encodeMD5(String data, String salt, int position){
        MD5Utils utils = new MD5Utils(salt.getBytes(), position);
        byte[] result = utils.encode(data.getBytes());
        String str = new String(result);
        log.debug("自定义MD5加密盐值的32位密钥的调试日志 ====>>" + str);
        return str;
    }

    /**
     * 首先调用Base64编码后再调用MD5加密
     * @param data
     * @return
     */
    public static String Base64AndMD5(String data, String salt, int position){
        String result = Base64Utils.encode(data.getBytes());
        MD5Utils utils = new MD5Utils(salt.getBytes(), position);
        byte[] getData = utils.encode(result.getBytes());
        String str = new String(getData);
        log.debug("先Base64编码后再执行MD5加密盐值的32位密钥的调试日志 ====>>" + str);
        return str;
    }

    /**
     * 首先调用MD5加密后继续调用Base64编码
     * @param data
     * @return
     */
    public static String MD5AndBase64(String data, String salt, int position){
        MD5Utils utils = new MD5Utils(salt.getBytes(), position);
        byte[] result = utils.encode(data.getBytes());
        String str = Base64Utils.encode(result);
        log.debug("先执行MD5加密盐值后再Base64编码的32位密钥的调试日志 ====>>" + str);
        return str;
    }

    /**
     * MD5加密, 不加盐
     * @param data
     * @return
     */
    public static String MD5WithSaltPosition(String data){
        MD5Utils utils = new MD5Utils();
        byte[] result = utils.encode(data.getBytes());
        String str = new String(result);
        log.debug("自定义MD5加密不加盐值的32位密钥的调试日志 ====>>" + str);
        return str;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值