Convert Base64 encoded md5 to a readable String

和自甴很熟 提交于 2019-12-04 20:47:11

It appears the above answer was for C#, as there is no such AppendFormat method for the StringBuilder class in Java.

Here is the correct solution:

public static String getMd5Hash(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
  MessageDigest md = MessageDigest.getInstance("MD5");
  byte[] thedigest = md.digest(str.getBytes("UTF-8"));

  StringBuilder hexString = new StringBuilder();

  for (int i = 0; i < thedigest.length; i++)
  {
      String hex = Integer.toHexString(0xFF & thedigest[i]);
      if (hex.length() == 1)
          hexString.append('0');

      hexString.append(hex);
  }

  return hexString.toString().toUpperCase();
}

decodeBase64 returns an array of bytes

To convert it to string of hex digits:

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!