How can I SHA512 a string in C#?

后端 未结 10 1216
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 18:35

I am trying to write a function to take a string and sha512 it like so?

public string SHA512(string input)
{
     string hash;

     ~magic~

     return has         


        
相关标签:
10条回答
  • 2020-12-08 19:05

    512/8 = 64, so 64 is indeed the correct size. Perhaps you want to convert it to hexadecimal after the SHA512 algorithm.

    See also: How do you convert Byte Array to Hexadecimal String, and vice versa?

    0 讨论(0)
  • 2020-12-08 19:05

    I'm not sure why you are expecting 128.

    8 bits in a byte. 64 bytes. 8 * 64 = 512 bit hash.

    0 讨论(0)
  • 2020-12-08 19:06

    You could use the System.Security.Cryptography.SHA512 class

    MSDN on SHA512

    Here is an example, straigt from the MSDN

    byte[] data = new byte[DATA_SIZE];
    byte[] result;
    SHA512 shaM = new SHA512Managed();
    result = shaM.ComputeHash(data);
    
    0 讨论(0)
  • 2020-12-08 19:07

    I used the following

    public static string ToSha512(this string inputString)
    {
            if (string.IsNullOrWhiteSpace(inputString)) return string.Empty;
            using (SHA512 shaM = new SHA512Managed())
            {
                return Convert.ToBase64String(shaM.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
            }
    }
    
    0 讨论(0)
  • 2020-12-08 19:10

    This is from one of my projects:

    public static string SHA512(string input)
    {
        var bytes = System.Text.Encoding.UTF8.GetBytes(input);
        using (var hash = System.Security.Cryptography.SHA512.Create())
        {
            var hashedInputBytes = hash.ComputeHash(bytes);
    
            // Convert to text
            // StringBuilder Capacity is 128, because 512 bits / 8 bits in byte * 2 symbols for byte 
            var hashedInputStringBuilder = new System.Text.StringBuilder(128);
            foreach (var b in hashedInputBytes)
                hashedInputStringBuilder.Append(b.ToString("X2"));
            return hashedInputStringBuilder.ToString();
        }
    }
    

    Please, note:

    1. SHA512 object is disposed ('using' section), so we do not have any resource leaks.
    2. StringBuilder is used for efficient hex string building.
    0 讨论(0)
  • 2020-12-08 19:13

    From the MSDN Documentation:
    The hash size for the SHA512Managed algorithm is 512 bits.

    0 讨论(0)
提交回复
热议问题