简体   繁体   中英

What is the equivalent of hashing Java code into C#?

I have a strange problem in getting equivalent hash code from C# code translated into Java. I don't know, what MessageDigest update method do. It should only update the contents of digest and should compute hash after calling digest.

Same thing I am doing in C# with SHAManaged512.ComputeHash(content). But I am not getting same hash code.

Following is the Java code.

public static String hash(String body, String secret) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(body.getBytes("UTF-8"));

        byte[] bytes = md.digest(secret.getBytes("UTF-8")); 

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

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

Following is C# Code

private byte[] ComputeContentHash(string contentBody)
{               
        using (var shaM = new SHA512Managed())       
        {
            var content = string.Concat(contentBody, Options.SecretKey);

            var hashedValue = shaM.ComputeHash(ToJsonStream(content));
            return hashedValue;
        }
}

public static Stream ToJsonStream(object obj)
{
   return new MemoryStream(Encoding.Unicode.GetBytes(obj.ToString()));
}

解决方案是放置第一个密钥并将其与有效负载数据连接起来。

I had the exact same issue. Its been two years since you asked but just in case someone comes across this question, here's the solution

public static string encryptHash(string APIkey, string RequestBodyJson)
    {
        var secretBytes = Encoding.UTF8.GetBytes(APIkey);
        var saltBytes = Encoding.UTF8.GetBytes(RequestBodyJson);

        using (var sHA256 = new SHA256Managed())
        {
            byte[] bytes = sHA256.ComputeHash(saltBytes.Concat(secretBytes).ToArray());

            //convert to hex
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            return builder.ToString();
        }
    }

Encoding.Unicode (which you are using in the C# ToJsonStream method) is not UTF8. It's UTF16. See MSDN . (Also keep in mind that UTF16 can be little or big endian.) You're looking for Encoding.UTF8 .

First thing to do is check if the byte array you're hashing is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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