使用C#和Java进行编码

huangapple go评论77阅读模式
英文:

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(@&quot;crc.xml&quot;);

    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 &lt; hash.Length; i++)
    {
         sb.Append(hash[i].ToString(&quot;X2&quot;));
    }
    Console.WriteLine(sb.ToString());

And my code in Java :

    string xmlstring = Files.readString(Paths.get(&quot;crc.xml&quot;));
    MessageDigest m = MessageDigest.getInstance(&quot;MD5&quot;);
    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);

huangapple
  • 本文由 发表于 2020年10月12日 22:07:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64319481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定