md5值是如何计算出来的

关于md5生产的写法, 多种多样,今天来看一个比较标准的写法,也即org.springframework.util中DigestUtils里面的写法。
所有的写法都是分两步,第一步是生产摘要的字节数组,固定是16个字节,128位

private static final String MD5_ALGORITHM_NAME = "MD5";

private static final char[] HEX_CHARS =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
   /**
     * Calculate the MD5 digest of the given bytes.
     * @param bytes the bytes to calculate the digest over
     * @return the digest
     */
    public static byte[] md5Digest(byte[] bytes) {
        return digest(MD5_ALGORITHM_NAME, bytes);
    }

    private static byte[] digest(String algorithm, byte[] bytes) {
        return getDigest(algorithm).digest(bytes);
    }

第二步是生成16进制字符

   private static char[] encodeHex(byte[] bytes) {
        char[] chars = new char[32];
        for (int i = 0; i < chars.length; i = i + 2) {
            byte b = bytes[i / 2];
            chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
            chars[i + 1] = HEX_CHARS[b & 0xf];
        }
        return chars;
    }

每一个字节会被转化成两个16进制字符,因此最后md5输出的字符串一共是32个字符,而且字符的范围呢, 全在HEX_CHARS中。

你可能感兴趣的:(java)