我有一个类负责根据我发送给它的内容生成哈希。但是,SHA256Managed.Create(text)
方法的返回始终返回 null
。
以下是我的代码:
using System.Security.Cryptography;
using System.Text;
namespace Autenticacao_no_ASP_.NET_MVC.Utils
{
public class Hash
{
public static string GerarHash(string texto)
{
SHA256 sha256 = SHA256Managed.Create(texto);
byte[] bytes = Encoding.UTF8.GetBytes(texto);
byte[] hash = sha256.ComputeHash(bytes);
StringBuilder result = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
result.Append(hash[i].ToString("X"));
}
return result.ToString();
}
}
}
sha256 which is being returned null.
最佳答案
创建 SHA256 的首选方法(使用 SHA256 来选择实现):
SHA256 sha256 = SHA256.Create();
Create
的参数是算法的名称 - 除非您使用基类来选择要使用的算法,否则您实际上不需要传递一个算法。要修复您的代码,请删除或使用正确的参数:
SHA256 sha256 = SHA256Managed.Create();
或
SHA256 sha256 = SHA256Managed.Create("SHA256");
请注意,这两个调用实际上都是由基础 SHA256
类实现的,首先只需选择“默认”实现。
参见 SHA256.Create以供引用。
关于C# 返回值 SHA256Managed 为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53990803/