Converting a md5 hash byte array to a string

前端 未结 7 1543
余生分开走
余生分开走 2021-01-31 13:28

How can I convert the hashed result, which is a byte array, to a string?

byte[] bytePassword = Encoding.UTF8.GetBytes(password);

using (MD5 md5 = MD5.Create())
         


        
7条回答
  •  抹茶落季
    2021-01-31 13:42

    I always found this to be the most convenient:

    string hashPassword = BitConverter.ToString(byteHashedPassword).Replace("-","");
    

    For some odd reason BitConverter likes to put dashes between bytes, so the replace just removes them.

    Update: If you prefer "lowercase" hex, just do a .ToLower() and boom.

    Do note that if you are doing this as a tight loop and many ops this could be expensive since there are at least two implicit string casts and resizes going on.

提交回复
热议问题