我试图在android中生成一个SHA256哈希,然后将其传递给ASP.NET API Web服务,并比较其中的哈希值.因此,我需要在Android中构造一个哈希,在ASP中提供相同的输入.NET将生成一个等价的哈希.我拼命想弄清楚我做错了什么.

以下是Android代码:

public String computeHash(String input) throws NoSuch算法rithmException{
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.reset();
    try{
      digest.update(input.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e){
      e.printStackTrace();
    }

    byte[] byteData = digest.digest(input.getBytes());
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < byteData.length; i++){
      sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }
    return sb.toString();
}

这是服务器上的代码(c#):

    private static string ComputeHash(string input, Hash算法rithm algorithm)
    {

        Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < hashedBytes.Length; i++)
        {
            sb.Append(String.Format("{0:x2}", hashedBytes[i]));
        }

        return sb.ToString();
    }

UPDATE:

public String computeHash(String input) throws NoSuch算法rithmException, UnsupportedEncodingException{
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.reset();

    byte[] byteData = digest.digest(input.getBytes("UTF-8"));
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < byteData.length; i++){
      sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }
    return sb.toString();
}

推荐答案

您的Java代码错误:您添加了两次输入字节.如果你要一次计算这个数字,你要么只需要拨打digest(bytes),要么在update(bytes)之后拨打digest()

Asp.net相关问答推荐

IIS HTTP 错误 500.19

如何在 ASP.NET WebForms 中实现 TDD

SignalR 不在服务器上使用 Session

如何使用特定视图(不是控制器名称)返回 ActionResult

使用域用户的 SQL 连接字符串?

带有 ASP.NET MVC 6 锚标记助手的 QueryString

Razor 主机工厂错误

VirtualPath 在当前应用程序根目录之外

ASP.NET RadioButton 与名称(组名)混淆

修改 web.config 时如何防止 ASP.NET 应用程序重新启动?

C# 7 本地函数未按预期工作且未显示错误

.NET AJAX 调用 ASMX 或 ASPX 或 ASHX?

回发不适用于 aspx 页面作为默认文档

MVC 模型布尔显示是或否

IIS - 无法通过 ip 地址而不是 localhost 访问页面

在后面的代码中删除 css 类

为什么 Controls 集合不提供所有 IEnumerable 方法?

在 Asp.Net MVC 5 中获取登录用户的用户 ID

SignalR 2.0 错误:无法加载文件或程序集 Microsoft.Owin.Security

ASP.NET MVC2/3 中runAllManagedModulesForAllRequests的正确用法是什么?