---
title: "字符串MD5值，适用于大文本的比较"
author: "MrCrapBag"
date: "2013-04-01T18:15:16Z"
tags: []
categories: ["编程语言"]
slug: "md5"
draft: false
lastmod: "2013-04-01T18:15:16Z"
id: 1840296
url: "https://mrcrapbag.iteye.com/blog/1840296"
---

public class Test
{
    protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static void main(String[] args)
    {
        MessageDigest messagedigest;
        try
        {
            messagedigest = MessageDigest.getInstance("MD5");
            messagedigest.update("aa".getBytes());

            System.out.println(bufferToHex(messagedigest.digest()));
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
    }

    private static String bufferToHex(byte bytes[])
    {
        int m = 0;
        int n = bytes.length;
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++)
        {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer)
    {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}