简体   繁体   English

在 Android/Java 和 C# 中计算 SHA256 Hash

[英]Compute SHA256 Hash in Android/Java and C#

I am trying to generate a SHA256 hash in android, that I then pass to an ASP.NET Web API web service and compare the hash there. I am trying to generate a SHA256 hash in android, that I then pass to an ASP.NET Web API web service and compare the hash there. As such, I need to construct a hash in Android, that given the same inputs in ASP.NET will generate an equivalent hash.因此,我需要在 Android 中构造一个 hash,在 Z9E0DA8438E1E38A1C30F4B76CE73B8ZDDZ 中给定相同的输入将生成等效的 Z08040FC577283948C。 I'm pulling my hair out trying to figure out what I'm doing wrong.我正在拔头发,试图找出我做错了什么。

Here's the Android code:这是 Android 代码:

public String computeHash(String input) throws NoSuchAlgorithmException{
    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();
}

Here's the C# code for the server:这是服务器的 C# 代码:

    private static string ComputeHash(string input, HashAlgorithm 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();
    }

Your Java code is wrong: you are adding the input bytes twice.您的 Java 代码是错误的:您添加了两次输入字节。 If you are calculating this in one go, you need to either call only digest(bytes) or call digest() after update(bytes) ;如果您一次性计算这个,您需要只调用digest(bytes)或在update(bytes)之后调用digest() update(bytes)

I was looking for a Kotlin version for my Android app.我正在为我的 Android 应用程序寻找Kotlin版本。

I could not find one;我找不到一个; here is what I came up with:这是我想出的:

fun String.getSha256(): String {
    val digest = MessageDigest.getInstance("SHA-256").apply { reset() }
    val byteData: ByteArray = digest.digest(this.toByteArray())
    return StringBuffer().apply {
        byteData.forEach {
            append(((it.toInt() and 0xff) + 0x100).toString(16).substring(1))
        }
    }.toString()
}

Migrating OP's solution from the question to an answer:将 OP 的解决方案从问题迁移到答案:

Here is the corrected Android/Java implementation (based on Nikolay Elenkov's answer ):这是更正的 Android/Java 实现(基于Nikolay Elenkov 的回答):

 public String computeHash(String input) throws NoSuchAlgorithmException, 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(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM