How to convert MD5 hash to string and use it as file name

I take the hash of the MD5 image file and I want to use the hash as the file name.

How to convert a hash to a string, which is a valid file name?

EDIT: toString()just gives "System.Byte []"

+5
source share
7 answers

How about this:

string filename = BitConverter.ToString(yourMD5ByteArray);

If you prefer a shorter file name without a hyphen, you can simply use:

string filename =
    BitConverter.ToString(yourMD5ByteArray).Replace("-", string.Empty);
+20
source

System.Convert.ToBase64String

- base 64 "/", , , . , , , - "/" .

string filename = Convert.ToBase64String(md5HashBytes).Replace("/","_");
+10

:

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)
+3

, , . / + ..

        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();
+3

:

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
+3

Base64 , Windows, ( , ).., base64 "a" "A", , , , , .

The best alternative is hexadecimal, as a bit converter class, or if you can use base32 encoding (which, after indenting both base64 and base32, and in the case of 128 bits, will give you similar names).

+1
source

Try the Base32 MD5 hash. This gives strings insensitive to file names.

    string Base32Hash(string input)
    {
        byte[] buf = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(input));
        return String.Join("", buf.Select(b => "abcdefghijklmonpqrstuvwxyz234567"[b & 0x1F]));
    }
+1
source

All Articles