简体   繁体   English

将Base64编码的md5转换为可读的字符串

[英]Convert Base64 encoded md5 to a readable String

I have a password stored in ldap as md5 hash: {MD5}3CydFlqyl/4AB5cY5ZmdEA== By the looks of it, it's base64 encoded. 我有一个作为md5哈希存储在ldap中的密码: {MD5}3CydFlqyl/4AB5cY5ZmdEA==从外观{MD5}3CydFlqyl/4AB5cY5ZmdEA== ,它是base64编码的。 How can i convert byte array received from ldap to a nice readable md5-hash-style string like this: 1bc29b36f623ba82aaf6724fd3b16718 ? 我如何将从ldap接收到的字节数组转换为如下所示的美观可读的md5-hash样式字符串: 1bc29b36f623ba82aaf6724fd3b16718 Is {MD5} a part of hash or ldap adds it and it should be deleted before decoding? {MD5}是hash还是ldap的一部分添加了它,应该在解码之前将其删除吗?

I've tried to use commons base64 lib, but when i call it like this: 我尝试使用commons base64 lib,但是当我这样调用它时:

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

It returns this - [B@24bf1f20 . 它返回此- [B@24bf1f20 Probably it's a wrong encoding, but when i convert it to UTF-8 i see unreadable chars. 可能是错误的编码,但是当我将其转换为UTF-8时,会看到不可读的字符。 So, what can i do to solve this? 那么,我该怎么解决呢?

It appears the above answer was for C#, as there is no such AppendFormat method for the StringBuilder class in Java. 似乎上述答案是针对C#的,因为Java中的StringBuilder类没有此类AppendFormat方法。

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 encodeBase64返回字节数组

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

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

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