Convert Base64 encoded md5 to a readable String

♀尐吖头ヾ 提交于 2019-12-06 16:46:21

问题


I have a password stored in ldap as md5 hash: {MD5}3CydFlqyl/4AB5cY5ZmdEA== By the looks of it, it's base64 encoded. How can i convert byte array received from ldap to a nice readable md5-hash-style string like this: 1bc29b36f623ba82aaf6724fd3b16718 ? Is {MD5} a part of hash or ldap adds it and it should be deleted before decoding?

I've tried to use commons base64 lib, but when i call it like this:

String b = Base64.decodeBase64(a).toString();

It returns this - [B@24bf1f20. Probably it's a wrong encoding, but when i convert it to UTF-8 i see unreadable chars. So, what can i do to solve this?


回答1:


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();
}



回答2:


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();
}


来源:https://stackoverflow.com/questions/12823079/convert-base64-encoded-md5-to-a-readable-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!