C# 返回值 SHA256Managed 为 NULL

标签 c# asp.net asp.net-mvc sha256

我有一个类负责根据我发送给它的内容生成哈希。但是,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/

相关文章:

c# - WCF 测试客户端 : Failed to add a service. 服务元数据可能无法访问。确保您的服务正在运行并公开元数据

c# - var 如何知道未定义的类型?

.net - ASP.NET MVC Posted Model 丢失接口(interface)属性值并且 ModelState 有错误。模型绑定(bind)限制?序列化问题?

c# - 如何在不下载内容的情况下执行 GET 请求?

ASP.NET core 2 充当反向代理用户重写中间件

asp.net - 如何将2个Web应用程序的机器 key 设置为相同?

c# - DateTime.Parse或Convert.ToDateTime不起作用

asp.net-mvc - 在MVC中,我如何返回IQueryable结果并使用操作在 View 中显示它

asp.net-mvc - VS 2015错误列表不跳转到MVC View

C# Protractor - 在另一个元素中查找元素