簡體   English   中英

SHA256 的十六進制輸入 hash

[英]Hex input to SHA256 hash

在線 hash 代碼可以使用 SHA256 從該站點獲得。

https://emn178.github.io/online-tools/sha256.html

1的hash代碼是“6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b”

但是,如果我們將 hash 代碼輸入類型設置為 1 個十六進制,則會出現“4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a”。

我可以在 c# 代碼中做第一個,但找不到可以做第二個的 c# 代碼。 你能幫忙嗎?

    static string ComputeSha256Hash(string rawData)
    {
        // Create a SHA256   
        using (SHA256 sha256Hash = SHA256.Create())
        {
            // ComputeHash - returns byte array  
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));

            // Convert byte array to a string   
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }

請試試這個,關鍵是將十六進制轉換為字節

        public static byte[] StringToByteArray(string hex)
        {
            int len = hex.Length;
            //the stackoverflow answer assumes you have even length,
            //so I insert a 0 if odd length.
            if (len % 2 == 1)
            {
                hex = hex.Insert(0, "0");
            }
            return Enumerable.Range(0, len)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

        static string ComputeSha256Hash(string rawData)
        {
            using (SHA256 sha256Hash = SHA256.Create())
            {
                byte[] bytes = sha256Hash.ComputeHash(StringToByteArray(rawData));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        static void Main(string[] args)
        {
            string hash = ComputeSha256Hash("1");
            Console.WriteLine(hash);
            Console.ReadKey();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM