0

I have implemented a web service(.asmx) using .NET framework that returns me a hash string

Here is the code:

     public string HashCode(string str)
        {
        string rethash = "";
        try
        {

            System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
            System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
            byte[] combined = encoder.GetBytes(str);
            hash.ComputeHash(combined);
            rethash = Convert.ToBase64String(hash.Hash);
        }
        catch (Exception ex)
        {
            string strerr = "Error in HashCode : " + ex.Message;
        }
        return rethash;
    }

In my Android app, I am taking the password from the user via EditText and again hashing it using SHA-1 algorithm. Considering the fact that I am providing the same password in both C# code and Android code will the hash strings returned by both be equal ?

Snippet of the Android code:

  private static String bytesToHexString(byte[] bytes) 
     {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

// generate a hash
  public void Sha(String password)
  {
    MessageDigest digest=null;
    String hash;

    try {
        digest = MessageDigest.getInstance("SHA-1");
        digest.update(password.getBytes());

        hash = bytesToHexString(digest.digest());

        Log.i("Eamorr", "result is " + hash);
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

  }

My main purpose is to basically compare the hash strings in both cases and if equal display a message saying "User is valid"

Can someone help me in this?

Thanks in advance

Name is Nilay
  • 2,743
  • 4
  • 35
  • 77
Parth Doshi
  • 4,200
  • 15
  • 79
  • 129

1 Answers1

1

The SHA-1 raw data will be the same, but it looks like your printable encoding is different: Base64 on the server, Hex(Base16) on the device. You need to use the same on both (or at least be able to decode both before you compare the bits).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • ok i will use Base16 on server then and write this line rethash = Convert.ToBase16String(hash.Hash); ..will that be fine? – Parth Doshi Nov 22 '11 at 04:54
  • Should be. Maybe minor things like padding or upper-case/lower-case. Just try it and unless it looks completely different you should be able to work from there. – Thilo Nov 22 '11 at 05:01
  • I tried but .NET doesn't contain a defination for Convert.ToBase16String().. i get an error over there..so now what how to make android code as base64? – Parth Doshi Nov 22 '11 at 05:04