简体   繁体   English

C# SHA-2 (512) Base64 编码哈希

[英]C# SHA-2 (512) Base64 encoded hash

Looking for a way to do the following in C# from a string.寻找一种从字符串在 C# 中执行以下操作的方法。

public static String sha512Hex(byte[] data) 公共静态字符串 sha512Hex(byte[] 数据)

Calculates the SHA-512 digest and returns the value as a hex string.计算 SHA-512 摘要并将值作为十六进制字符串返回。

Parameters: data - Data to digest Returns: SHA-512 digest as a hex string参数:data - 要摘要的数据返回:SHA-512 摘要作为十六进制字符串

    private static string GetSHA512(string text)
    {
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        byte[] message = UE.GetBytes(text);
        SHA512Managed hashString = new SHA512Managed();
        string encodedData = Convert.ToBase64String(message);
        string hex = "";
        hashValue = hashString.ComputeHash(UE.GetBytes(encodedData));
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

Would System.Security.Cryptography.SHA512 be what you need? System.Security.Cryptography.SHA512是您需要的吗?

var alg = SHA512.Create();
alg.ComputeHash(Encoding.UTF8.GetBytes("test"));
BitConverter.ToString(alg.Hash).Dump();

Executed in LINQPad produces:LINQPad 中执行产生:

EE-26-B0-DD-4A-F7-E7-49-AA-1A-8E-E3-C1-0A-E9-92-3F-61-89-80-77-2E-47-3F-88-19-A5-D4-94-0E-0D-B2-7A-C1-85-F8-A0-E1-D5-F8-4F-88-BC-88-7F-D6-7B-14-37-32-C3-04-CC-5F-A9-AD-8E-6F-57-F5-00-28-A8-FF EE-26-B0-DD-4A-F7-E7-49-AA-1A-8E-E3-C1-0A-E9-92-3F-61-89-80-77-2E-47-3F-88- 19-A5-D4-94-0E-0D-B2-7A-C1-85-F8-A0-E1-D5-F8-4F-88-BC-88-7F-D6-7B-14-37-32- C3-04-CC-5F-A9-AD-8E-6F-57-F5-00-28-A8-FF

To create the method from your question:要根据您的问题创建方法:

public static string sha512Hex(byte[] data)
{
    using (var alg = SHA512.Create())
    {
        alg.ComputeHash(data);
        return BitConverter.ToString(alg.Hash);
    }
}

Got this to work.得到这个工作。 Taken from here and modified a bit.取自here并稍作修改。

    public static string CreateSHAHash(string Phrase)
    {
        SHA512Managed HashTool = new SHA512Managed();
        Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
        Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
        HashTool.Clear();
        return Convert.ToBase64String(EncryptedBytes);
    }

Better memory management:更好的内存管理:

    public static string SHA512Hash(string value)
    {
        byte[] encryptedBytes;

        using (var hashTool = new SHA512Managed())
        {
            encryptedBytes = hashTool.ComputeHash(System.Text.Encoding.UTF8.GetBytes(string.Concat(value)));
            hashTool.Clear();
        }

        return Convert.ToBase64String(encryptedBytes);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM