SHA256 hash smillar to .Net hash

151 Views Asked by At

I have am doing an Oauth App, where in few parts the hash is calculated via a .Net application, following is the .Net code to compute the hash

public static string GetBase64CodeChallange(string str)
{
    using (SHA256 sha256Hash = SHA256.Create())
    {
        byte[] challengeBytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(str));

        string s = Convert.ToBase64String(challengeBytes);
        s = s.Split('=')[0];
        s = s.Replace('+', '-');
        s = s.Replace('/', '_');
        return s;
    }
}

I want a similar version in android. I have R&D around the web and no solution yet of the same. Following the java code which is producing a different result. The android version string needs to be same as .Net version.

String str1 = "str";
            String outHash = "95e5f0b6988ec703e832172f70ce7dc7";
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] array = md.digest(str1.getBytes("UTF-8"));
                StringBuilder sb = new StringBuilder();
                for (byte b : array) {
                    sb.append(String.format("%02X", b));
                }
                System.out.println(sb.toString());
                System.out.println(sb.toString().equalsIgnoreCase(outHash));
            } catch (Exception e) {
                e.printStackTrace();
            }

Android - Java code

Please help

1

There are 1 best solutions below

1
On

It's hard to test because you only need to get one thing wrong, and the hash is completely different because they are designed that way. You never get to think "I'm getting closer" until it's exactly right.

Make sure you use the same encoding on the byteArray, use the same hashing algorithm (the .NET example here is SHA-256 and your Java one is MD5)