英文:
Encoding with C# and Java
问题
C#代码部分:
string xmlString = System.IO.File.ReadAllText(@"crc.xml");
byte[] bytes = Encoding.ASCII.GetBytes(xmlString);
// 步骤 1,计算输入的 MD5 哈希值
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] hash = md5.ComputeHash(bytes);
// 步骤 2,将字节数组转换为十六进制字符串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
Console.WriteLine(sb.ToString());
Java代码部分:
String xmlstring = Files.readString(Paths.get("crc.xml"));
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] digest = m.digest(xmlstring.getBytes());
String hash = new BigInteger(1, digest).toString(16);
System.out.println(hash);
C#的结果:
F5F8B2F361FEA6EA30F24BEBAA5BDE3A
但是在Java中的结果:
8fb40aad49fbf796b82a2faa11cda764
我做错了什么?
英文:
I have got to make the same function in Java and C#, but the result are not the same.
My code in C# :
string xmlString = System.IO.File.ReadAllText(@"crc.xml");
byte[] bytes = Encoding.ASCII.GetBytes(xmlString);
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] hash = md5.ComputeHash(bytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
Console.WriteLine(sb.ToString());
And my code in Java :
string xmlstring = Files.readString(Paths.get("crc.xml"));
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] digest = m.digest(xmlstring.getbytes());
String hash = new BigInteger(1, digest).toString(16);
System.out.println(hash);
In C# I have this result :
>F5F8B2F361FEA6EA30F24BEBAA5BDE3A
But in Java I have this result :
>8fb40aad49fbf796b82a2faa11cda764
What I'm doing wrong?
答案1
得分: 1
Codebrane说。使用
byte[] bytes = Encoding.UFT8.GetBytes(xmlString);
而不是
byte[] bytes = Encoding.ASCII.GetBytes(xmlString);
英文:
Codebrane say it. Use
byte[] bytes = Encoding.UFT8.GetBytes(xmlString);
instead of
byte[] bytes = Encoding.ASCII.GetBytes(xmlString);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论