I am taking the MD5 hash of an image file and I want to use the hash as a filename.
How do I convert the hash to a string that is valid filename?
EDIT: toString()
just gives "System.Byte[]"
这个怎么样:
string filename = BitConverter.ToString(yourMD5ByteArray);
如果您更喜欢没有连字符的较短文件名,那么您可以使用:
string filename =
BitConverter.ToString(yourMD5ByteArray).Replace("-", string.Empty);
As a commenter pointed out -- normal base 64 encoding can contain a '/' character, which obivously will be a problem with filenames. However, there are other characters that are usable, such as an underscore - just replace all the '/' with an underscore.
string filename = Convert.ToBase64String(md5HashBytes).Replace("/","_");
Try this:
Guid guid = new Guid(md5HashBytes);
string hashString = guid.ToString("N");
// format: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
string hashString = guid.ToString("D");
// format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
string hashString = guid.ToString("B");
// format: {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
string hashString = guid.ToString("P");
// format: (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
尝试这个:
string Hash = Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("sample")));
//input "sample" returns = Xo/5v1W6NQgZnSLphBKb5g==
或者
string Hash = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("sample")));
//input "sample" returns = 5E-8F-F9-BF-55-BA-35-08-19-9D-22-E9-84-12-9B-E6
这可能是最安全的文件名。你总是得到一个十六进制字符串,而不必担心 / 或 + 等。
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(inputString));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
string hashed = sBuilder.ToString();
如果这是 Windows,从技术上讲,使用 Base64 是不好的,文件名不区分大小写(至少在资源管理器视图中).. 但在 base64 中,“a”与“A”不同,这意味着这可能不太可能,但你最终会得到更高的速率碰撞..
更好的选择是像 bitconverter 类这样的十六进制,或者如果您可以使用 base32 编码(在从 base64 和 base32 中删除填充后,在 128 位的情况下,将为您提供相似长度的文件名)。
尝试 MD5 的 Base32 哈希。它提供文件名安全的不区分大小写的字符串。
string Base32Hash(string input)
{
byte[] buf = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(input));
return String.Join("", buf.Select(b => "abcdefghijklmonpqrstuvwxyz234567"[b & 0x1F]));
}