【问题标题】:SHA256 Hashing of String **With Update** (UTF8 String)字符串的 SHA256 散列**使用更新**(UTF8 字符串)
【发布时间】:2020-11-21 01:01:09
【问题描述】:

我正在尝试通过更新从控制台输入散列字符串(类似于节点加密中的);

我在 Node JS 中使用过这个。如何在 C# 中复制此行为

import { createHmac } from 'crypto';
Hash(password: string, update: string): string {
    return createHmac('sha256','StringSecret').update('StringKey').digest('hex');
}

我试过this Solution 是这样的。

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();  
            }  
        }  
                 
    }  
  
}  

但它不允许任何更新;

【问题讨论】:

  • 如果这是一个现场制作项目,请考虑一些算法,它不会被认为是“不安全”的密码。

标签: c# .net hash cryptography sha256


【解决方案1】:

据我从Node docs 得知,更新函数只是将新数据添加到哈希函数的输入中。如果确实如此,您只需在将数据传递给散列方法之前附加数据即可完成此操作。

string hashedData = ComputeSha256Hash("StringSecret" + "StringKey");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 2018-06-12
    • 2011-07-28
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2012-10-14
    • 2016-04-06
    相关资源
    最近更新 更多