[英]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.