美文网首页
Android 常用工具类之 DigestUtils

Android 常用工具类之 DigestUtils

作者: Kevin_小飞象 | 来源:发表于2021-06-10 14:39 被阅读0次

DigestUtils 工具类,此工具类不是网上大家用烂的那一份,是博主亲自编写,亲自测试,代码简洁清晰,可满足日常开发。

import java.security.MessageDigest;

/**
 * Created on 2021/4/13 14:24
 *
 * @author Gong Youqiang
 */
public class DigestUtils {
    /**
     * Used to build output as Hex
     */
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'                         };

    private DigestUtils() {
        throw new AssertionError();
    }

    /**
     * encode By MD5
     *
     * @param str    字符串
     * @return String
     */
    public static String md5(String str) {

        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return new String(encodeHex(messageDigest.digest()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
     * The returned array will be double the length of the passed array, as it takes two characters to represent any
     * given byte.
     *
     * @param data a byte[] to convert to Hex characters
     * @return A char[] containing hexadecimal characters
     */
    protected static char[] encodeHex(final byte[] data) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return out;
    }
}

相关文章

网友评论

      本文标题:Android 常用工具类之 DigestUtils

      本文链接:https://www.haomeiwen.com/subject/izxclltx.html