Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

asp.net - 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. As such, I need to construct a hash in Android, that given the same inputs in ASP.NET will generate an equivalent hash. I'm pulling my hair out trying to figure out what I'm doing wrong.

Here's the Android code:

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

AND HERE's THE CODE ON 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();
    }

UPDATE: Here is the corrected Android/Java implementation (thank you 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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your Java code is wrong: you are adding the input bytes twice. If you are calculating this in one go, you need to either call only digest(bytes) or call digest() after update(bytes);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...