6

I want to generate the hash code from a string,e.g."咖啡",but the hashcode I get from python and c# is different,the one from python is what I want

c#

String str = "咖啡";
MD5 m = MD5.Create();
byte[] data = m.ComputeHash(Encoding.Default.GetBytes(str));
StringBuilder sbuilder = new StringBuilder();
for(int i=0;i<data.Length;i++){
  sbuilder.Append(data[i].ToString("x2"));
}
byte[] hex = Encoding.Default.GetBytes(str);
StringBuilder hex_builder = new StringBuilder();
foreach(byte a in hex){
  hex_builder.Append("{0:x2}",a);
}
//md5 hash code
Response.Write(sbuilder.ToString());
//binary string
Response.Write(hex_builder.ToString());

python

#coding:utf8
str = '咖啡'
m = hashlib.md5()
m.update(str)
#md5 hashcode
print m.hexdigest()
#binary string
print ' '.join(["%02x"%ord(x) for x in str])

binary string is e5 92 96 e5 95 a1 both in c# and python

md5 hash code:

(c#)a761914f9760af3c112e24f08dea1b16

(python)3b7daa58a1fecdf5ba4d94d539fbb4d5

2
  • the c# passes a byte array to ComputeHash, whereas the python update takes string. can you create a byte array in python and pass that to update? Commented May 17, 2011 at 7:57
  • FYI - i just ran your python code on my pc (python 2.5) and I get a761914f9760af3c112e24f08dea1b16 as the hash - although I had to remove the #coding:utf8 Commented May 17, 2011 at 8:08

2 Answers 2

5

The string encoding might be different; therefore when you convert string to byte[] you probably get different values. Try printing those to see if they are the same.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought the default encoding in .net is utf16,and maybe I set python encoding to utf8(#coding:utf8 at top of the file),but the byte array is same: e5 92 96 e5 95 a1
4

Had same problem. Was able to encode the text as "UTF-16LE" and the C# and Python both produced the same result.

def getMD5(text):
    encoding = text.encode("UTF-16LE")
    md5 = hashlib.md5()
    md5.update(encoding)
    return md5.hexdigest()

1 Comment

I need my C# code to return the value provided by the python code. Do you know of a way to alter the C# code to do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.