将MD5数组转换为字符串java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3752981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:25:35  来源:igfitidea点击:

Convert MD5 array to String java

javamd5

提问by Andrew

I know that there is a lot of similar topics, but still... can someone provide me a working example of method which generates MD5 String.
I'm currently using MessageDigest, and I'm doing the following to get a string

我知道有很多类似的主题,但仍然......有人可以为我提供一个生成 MD5 字符串的方法的工作示例。
我目前正在使用 MessageDigest,我正在执行以下操作以获取字符串

sun.misc.BASE64Encoder().encode(messageDigest.digest())  

I guess there is some better way to do that.
Thanks in advance!

我想有一些更好的方法可以做到这一点。
提前致谢!

采纳答案by Jigar Joshi

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] arr = md.digest(bytesOfMessage);
return Base64.getEncoder().encodeToString(arr);

note: md5 is not considered as good hash algorithm anymore, consider choosing SHAs

注意:md5 不再被认为是好的哈希算法,请考虑选择 SHA

回答by Bozho

I'd use commons-codec

我会使用公共编解码器

  • Base64 - Base64.encodeBase64(digestBytes)
  • Hex-string - Hex.encodeHex(digestBytes)
  • Base64 - Base64.encodeBase64(digestBytes)
  • 六角字符串 - Hex.encodeHex(digestBytes)

回答by Grodriguez

// Convert to hex string
StringBuffer sb = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
    if ((0xff & messageDigest[i]) < 0x10) {
        sb.append('0');
    }
    sb.append(Integer.toHexString(0xff & messageDigest[i]));
}
String md5 = sb.toString();

This assumes you actually want your MD5 printed as an hex string, not BASE64-encoded. That's the way it is normally represented.

这假设您实际上希望将 MD5 打印为十六进制字符串,而不是 BASE64 编码。这就是它通常的表示方式。

回答by Pau Kou

I've seen next solution:

我已经看到下一个解决方案:

    byte[] digest = md.digest(someDataByteArray);
    StringBuilder hex = new StringBuilder();
    for (byte b : digest) {
        hex.append(String.format("%02x", b));
    }

回答by WesternGun

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;

...
String input = "westerngun";
MessageDigest digest = MessageDigest.getInstance("MD5"); // not thread-safe, create instance for each thread
byte[] result = digest.digest(input.getBytes()); // get MD5 hash array, could contain negative
String hex = DatatypeConverter.printHexBinary(result).toLowerCase(); // convert byte array to hex string

If you want a number:

如果你想要一个数字:

Integer number = Integer.parseInt(hex, 16); // parse hex number to integer. If overflowed, use Long.parseLong()