How can I SHA512 a string in C#?

后端 未结 10 1200
伪装坚强ぢ
伪装坚强ぢ 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:14

    Your code is correct, but you should dispose of the SHA512Managed instance:

    using (SHA512 shaM = new SHA512Managed())
    {
       hash = shaM.ComputeHash(data);
    }
    

    512 bits are 64 bytes.

    To convert a string to a byte array, you need to specify an encoding. UTF8 is okay if you want to create a hash code:

    var data = Encoding.UTF8.GetBytes("text");    
    using (...
    
    0 讨论(0)
  • 2020-12-08 19:14

    You might try these lines:

    public static string GenSHA512(string s, bool l = false)
    {
        string r = "";
        try
        {
            byte[] d = Encoding.UTF8.GetBytes(s);
            using (SHA512 a = new SHA512Managed())
            {
                byte[] h = a.ComputeHash(d);
                r = BitConverter.ToString(h).Replace("-", "");
            }
            r = (l ? r.ToLowerInvariant() : r);
        }
        catch
        {
    
        }
        return r;
    }
    
    1. It is disposed at the end
    2. It's safe
    3. Supports lower case
    0 讨论(0)
  • 2020-12-08 19:17
    UnicodeEncoding UE = new UnicodeEncoding();            
            byte[] message = UE.GetBytes(password);
            SHA512Managed hashString = new SHA512Managed();
            string hexNumber = "";
            byte[]  hashValue = hashString.ComputeHash(message);
            foreach (byte x in hashValue)
            {
                hexNumber += String.Format("{0:x2}", x);
            }
            string hashData = hexNumber;
    
    0 讨论(0)
  • 2020-12-08 19:22

    Instead of WinCrypt-API using System.Security.Cryptography, you can also use BouncyCastle:

    public static byte[] SHA512(string text)
    {
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
    
        Org.BouncyCastle.Crypto.Digests.Sha512Digest digester = new Org.BouncyCastle.Crypto.Digests.Sha512Digest();
        byte[] retValue = new byte[digester.GetDigestSize()];
        digester.BlockUpdate(bytes, 0, bytes.Length);
        digester.DoFinal(retValue, 0);
        return retValue;
    }
    

    If you need the HMAC-version (to add authentication to the hash)

    public static byte[] HmacSha512(string text, string key)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
    
        var hmac = new Org.BouncyCastle.Crypto.Macs.HMac(new Org.BouncyCastle.Crypto.Digests.Sha512Digest());
        hmac.Init(new Org.BouncyCastle.Crypto.Parameters.KeyParameter(System.Text.Encoding.UTF8.GetBytes(key)));
    
        byte[] result = new byte[hmac.GetMacSize()];
        hmac.BlockUpdate(bytes, 0, bytes.Length);
        hmac.DoFinal(result, 0);
    
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题