[英]Convert Base64 encoded md5 to a readable String
我有一個作為md5哈希存儲在ldap中的密碼: {MD5}3CydFlqyl/4AB5cY5ZmdEA==
從外觀{MD5}3CydFlqyl/4AB5cY5ZmdEA==
,它是base64編碼的。 我如何將從ldap接收到的字節數組轉換為如下所示的美觀可讀的md5-hash樣式字符串: 1bc29b36f623ba82aaf6724fd3b16718
? {MD5}
是hash還是ldap的一部分添加了它,應該在解碼之前將其刪除嗎?
我嘗試使用commons base64 lib,但是當我這樣調用它時:
String b = Base64.decodeBase64(a).toString();
它返回此- [B@24bf1f20
。 可能是錯誤的編碼,但是當我將其轉換為UTF-8時,會看到不可讀的字符。 那么,我該怎么解決呢?
似乎上述答案是針對C#的,因為Java中的StringBuilder類沒有此類AppendFormat方法。
這是正確的解決方案:
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();
}
encodeBase64返回字節數組
要將其轉換為十六進制數字字符串:
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.