Converting SHA1 from c# to android

313 Views Asked by At

I need to take this C# code and make the same hash in android:

string result = "2-" + Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes(password)));

I am trying to get this done for hours and still its hashing different codes. Thanks for your answers.

1

There are 1 best solutions below

1
On BEST ANSWER

Here we go:

try {
    String password = "qwkld67U";
    MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
    sha1.update(password.getBytes("UTF-16LE"));
    String result = "2-" + Base64.encodeToString(sha1.digest(), Base64.DEFAULT);
    Log.i("SHA1", result);
} catch (Exception e) {
    throw new RuntimeException(e);
}

The output is:

I/SHA1: 2-BePLL+2eth1YOoIcbA5sfzD8Yuw=

Most people get the string encoding wrong. Encoding.Unicode in .NET is a UTF-16 encoding without byte order mark. The Java equivalent is UTF-16LE (and not just UTF-16, which has a byte order mark at the start).

And regarding the security anti-pattern. I know you don't care. But it's probably even worse than I suspected in my comment (hashing without salt). If you transmit the hashed password to a server and compare it there against the hashed password, it completely defeats the purpose of hashing the password in the first place. It's far better to transmit the clear text password over an encrypted connection than to transmit the hashed password. Let those in charge of the security design know.