[英]SHA256 Hashing of String **With Update** (UTF8 String)
我正在嘗試 Hash 來自控制台輸入的字符串並進行更新(類似於節點加密中的字符串);
我在 Node JS 中使用過這個。 如何在 C# 中復制此行為
import { createHmac } from 'crypto';
Hash(password: string, update: string): string {
return createHmac('sha256','StringSecret').update('StringKey').digest('hex');
}
我已經嘗試過這個解決方案,它就像這樣。
using System.Text;
using System.Security.Cryptography;
namespace HashConsoleApp
{
class Program
{
static void Main(string[] args)
{
string plainData = "Password";
Console.WriteLine("Raw data: {0}", plainData);
string hashedData = ComputeSha256Hash(plainData);
Console.WriteLine("Hash {0}", hashedData);
Console.WriteLine(ComputeSha256Hash("Password"));
Console.ReadLine();
}
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();
}
}
}
}
但它不允許任何更新;
從節點文檔中我可以看出,更新 function 只是將新數據添加到 hash 函數的輸入中。 如果確實如此,您只需在將數據傳遞給散列方法之前附加數據即可完成此操作。
string hashedData = ComputeSha256Hash("StringSecret" + "StringKey");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.