python 和 c# 中的字节字符串相同,但 md5 哈希码不同
我想从字符串生成哈希码,例如“咖啡”,但是我从 python 和 c# 获得的哈希码是不同的,来自 python 的哈希码是我想要的
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])
二进制字符串 是 e5 92 c# 和 python 中的 96 e5 95 a1
md5 哈希码:
(c#)a761914f9760af3c112e24f08dea1b16
(python)3b7daa58a1fecdf5ba4d94d539fbb4d5
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符串编码可能不同;因此,当您将 string 转换为 byte[] 时,您可能会得到不同的值。尝试打印这些看看它们是否相同。
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.
有同样的问题。能够将文本编码为“UTF-16LE”,并且 C# 和 Python 都产生相同的结果。
Had same problem. Was able to encode the text as "UTF-16LE" and the C# and Python both produced the same result.