简体   繁体   English

从Message Digest获取MD5字符串

[英]Get MD5 String from Message Digest

I understand how it works but if I want to print out the MD5 as String how would I do that? 我理解它是如何工作的但是如果我想将MD5打印成String我该怎么做?

public static void getMD5(String fileName) throws Exception{
    InputStream input =  new FileInputStream(fileName);
    byte[] buffer = new byte[1024];

    MessageDigest hash = MessageDigest.getInstance("MD5");
    int read;
    do {
        read = input.read(buffer);
        if (read > 0) {
            hash.update(buffer, 0, read);
        }
    } while (read != -1);
    input.close();
}

你可以减少写作:

String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))
    String input = "168";
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] md5sum = md.digest(input.getBytes());
    String output = String.format("%032X", new BigInteger(1, md5sum));

or 要么

DatatypeConverter.printHexBinary( MessageDigest.getInstance("MD5").digest("a".getBytes("UTF-8")))

Try this 试试这个

StringBuffer hexString = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.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]));
    }
}

You can also use Apache Commons Codec library. 您还可以使用Apache Commons Codec库。 This library includes methods public static String md5Hex(InputStream data) and public static String md5Hex(byte[] data) in the DigestUtils class. 该库包含public static String md5Hex(InputStream data)public static String md5Hex(byte[] data)DigestUtils No need to invent this yourself ;) 不需要自己发明;)

First you need to get the byte[] output of the MessageDigest : 首先,您需要获取MessageDigestbyte[]输出:

byte[] bytes = hash.digest();

You can't easily print this though (with eg new String(bytes) ) because it's going to contain binary that won't have good output representations. 你不能轻易打印这个(例如new String(bytes) ),因为它将包含不具有良好输出表示的二进制文件。 You can convert it to hex for display like this however: 您可以将其转换为十六进制,以便显示如下:

StringBuilder sb = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
    sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
    sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
}
String hex = sb.toString();

With the byte array, result from message digest: 使用字节数组,来自消息摘要的结果:

...
byte hashgerado[] = md.digest(entrada);
...

for(byte b : hashgerado)
    System.out.printf("%02x", Byte.toUnsignedInt(b));

Result (for example): 结果(例如):
89e8a9f68ad3c4bba9b9d3581cf5201d 89e8a9f68ad3c4bba9b9d3581cf5201d

/**
 * hashes:
 * e7cfa2be5969e235138356a54bad7fc4
 * 3c9ec110aa171b57bb41fc761130822c
 *
 * compiled with java 8 - 12 Dec 2015
 */
public static String generateHash() {
    long r = new java.util.Random().nextLong();
    String input = String.valueOf(r);
    String md5 = null;

    try {
        java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());
        //Converts message digest value in base 16 (hex)
        md5 = new java.math.BigInteger(1, digest.digest()).toString(16);
    }
    catch (java.security.NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return md5;
}

FYI... FYI ...

In certain situations this did not work for me 在某些情况下,这对我不起作用

md5 = new java.math.BigInteger(1, digest.digest()).toString(16);

but this did 但这样做了

StringBuilder sb = new StringBuilder();

for (int i = 0; i < digest.length; i++) {
    if ((0xff & digest[i]) < 0x10) {
        sb.append("0").append(Integer.toHexString((0xFF & digest[i])));
    } else {
        sb.append(Integer.toHexString(0xFF & digest[i]));
    }
}

String result = sb.toString();

Shortest way: 最短的方式:

String toMD5(String input) {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] raw = md.digest(input.getBytes());
    return DatatypeConverter.printHexBinary(raw);
}

Just remember to handle the exception. 只记得处理异常。

This is another version of @anything answer: 这是@anything答案的另一个版本:

StringBuilder sb = new StringBuilder();

for (int i = 0; i < digest.length; i++) {
    if ((0xff & digest[i]) < 0x10) {
        sb.append("0").append(Integer.toHexString((0xFF & digest[i])));
    } else {
        sb.append(Integer.toHexString(0xFF & digest[i]));
    }
}

String result = sb.toString();

Call hash.digest() to finish the process. 调用hash.digest()来完成该过程。 It will return an array of bytes. 它将返回一个字节数组。

You can create a String from a byte[] using a String constructor, however if you want a hex string you'll have to loop through the byte array manually and work out the characters. 您可以使用String构造函数从byte[]创建String,但是如果您想要一个十六进制字符串,则必须手动遍历字节数组并计算出字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM