簡體   English   中英

如何正確創建SHA256哈希?

[英]How to properly create a SHA256 Hash?

我正在實現SSO,在其中我必須計算字符串的SHA256,然后將哈希發送回給終結點並在終結點處對用戶進行身份驗證。 我通過執行以下操作使SHA1正常工作:

 var hash = SHA1.Create();
 var encoder = new ASCIIEncoding();
 byte[] combined = encoder.GetBytes(encryptedTokenStr);
 hash.ComputeHash(combined);
 string delimitedHexHash = BitConverter.ToString(hash.Hash);
 string completedSha1Hash = delimitedHexHash.Replace("-", "");

但是,如果我將哈希算法類型更改為SHA256而在另一個系統上,將哈希算法更改為SHA256 Salted (Suffix)不知道這是否與SHA256相同嗎? 以下代碼無法正常工作,這意味着它無法在另一端對用戶進行身份驗證:

var hash = SHA256.Create();
var encoder = new UTF8Encoding();
byte[] combined = encoder.GetBytes(encryptedTokenStr);
hash.ComputeHash(combined);
string delimitedHexHash = BitConverter.ToString(hash.Hash);
string completedSha1Hash = delimitedHexHash.Replace("-", "");

SHA256與“ SHA256 Salted”不同。

好吧,從技術上講,它們都是SHA256,只是輸入有所不同。 在執行SHA256時,您對數據本身進行哈希處理。 在進行“鹽腌”(與使用哪種哈希函數無關)時,您首先要在輸入中添加一些“鹽”(添加可能會有所不同,但大多數情況下只是串聯;“后綴”提示在添加鹽之后輸入),然后對所得數據進行哈希處理。

更多詳細信息: https : //en.wikipedia.org/wiki/Salt_%28cryptography%29

在我的解決方案中,我使用以下內容(准備好復制和粘貼):

using System;
using System.Security.Cryptography;
using System.Text;

public string ComputeHash(string plainText, byte[] salt = null)
    {
        int minSaltLength = 4;
        int maxSaltLength = 16;

        byte[] saltBytes = null;

        if (salt != null)
        {
            saltBytes = salt;
        }
        else
        {
            Random r = new Random();
            int len = r.Next(minSaltLength, maxSaltLength);
            saltBytes = new byte[len];

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetNonZeroBytes(saltBytes);
            }
        }
        byte[] plainData = ASCIIEncoding.UTF8.GetBytes(plainText);
        int plainLength = plainData.Length;
        int saltLength = saltBytes.Length;
        byte[] plainDataAndSalt = new byte[plainLength + saltLength];
        Array.Copy(plainData, 0, plainDataAndSalt, 0, plainLength);
        Array.Copy(saltBytes, 0, plainDataAndSalt, plainLength, saltLength);

        byte[] hashValue = null;

        using (SHA256Managed sha2 = new SHA256Managed())
        {
             hashValue = sha2.ComputeHash(plainDataAndSalt);
        }

        int hashLength = hashValue.Length;
        byte[] result = new byte[hashLength + saltLength];
        Array.Copy(hashValue, 0, result, 0, hashLength);
        Array.Copy(saltBytes, 0, result, hashLength, saltLength);

        return ASCIIEncoding.UTF8.GetString(result);
    }

您的問題/問題的解決方案:

string hash = hash.ComputeHash("your string");

或者,如果服務器為您提供了鹽字符串:

byte[] salt = ASCIIEncoding.UTF8.GetBytes("server salt string in plaintext");
string hash = hash.ComputeHash("your string to hash", salt);

然后將哈希返回到服務器。

暫無
暫無

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

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