I have a C# WebService and a (Java) Android Application. Is there a SIMPLE hash function that produces the same result between these two languages? The simplest C# hash is a String.GetHashCode(), but I can’t replicate it in Java. The simplest Java hash is not simple at all. And I don’t know if I can replicate it exactly in C#.
In case it’s relevant, I’m hashing passwords before sending it across the internet. I’m currently using Encode64, but that’s obviously not secure since we can reverse it.
EDIT: Ok, I settled on using SHA256. Incase somebody else needs a quick solution, here are the code that I used, considering that I wanted both the C# and the Java to output the exact same string and I needed the simplest possible solution.
Java
public String Hash(String s)
{
StringBuffer sb = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(s.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
.substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return sb.toString();
}
C#
public static string Hash(String s)
{
HashAlgorithm Hasher = new SHA256CryptoServiceProvider();
byte[] strBytes = Encoding.UTF8.GetBytes(s);
byte[] strHash = Hasher.ComputeHash(strBytes);
return BitConverter.ToString(strHash).Replace("-","").ToLowerInvariant().Trim();
}
Thanks guys! 🙂
First, the kind of hashes implemented by
String.GetHashCode()andString.hashCode()are not designed to be used for this kind of thing. For a start, they only hash to a 32 but number (at least in the Java case), so there is a significant risk of collisions. In this case, if two different passwords map to the same hash … then someone has a chance of 1 in 2^32 that a randomly chosen password will be accepted. (And the flip side is that if the bad guy can intercept the 32 bit hash for a valid password, they have a big “leg up” in guessing what the original password was!)Second, sending a crypto hash (such as produced by MD5, SHA-256, etc), is probably not going to solve your security problems … unless you send the hash over SSL or something. Sure, the bad guy won’t be able to recover the original password was, but they CAN intercept and use the hash in a “replay” attack. (There are ways to combat this, but they either require a shared secret key, or use of public/private key encryption … and you HAVE TO know what you are doing if you want this to be secure.)
In short, you need to discuss your whole problem and proposed solution(s) with someone who has solid security expertise.
If you really think that this is not a security issue, then an MD5 hash should be fine. But don’t say that you weren’t warned …
(But don’t use a simple 32-bit hashcode because that is barely more secure than base64.)