简体   繁体   中英

How to get same result with Dart sha256 and C# sha256?

I have to convert string to sha256 in dart. For example I use String a = "2424242401224672"; In my code below I get an result as; digest: 7b73641404a8fe6a4b1161a85db736be2a6c07a046109b993186f7a22190bf13

The Code:

  String a = "2424242401224672";
  var bytes = utf8.encode(a.hashCode.toString());
  var digest = sha256.convert(bytes);
  print("digest: $digest");

In other party use c# for sha256. They get bytes from string(object) using c# MemoryStream, BinaryFormatter and XMLSerilizer.

But when I show my result they told me that they get different result in C# sha256?

How to get same result with Dart sha256 and C# sha256?

Update:

The string "2424242401224672" in CSharp has a sha256 value as: DE4841A9E623AF7D5C598A67C2461702485F6B77C3EB5448FA5E0DDF074C70D8

Update-2:

The csharp code:

private static string ComputeHash(byte[] objectAsBytes)
{                        
    try
    {
        SHA256 shaM = new SHA256Managed();
        byte[] result = shaM.ComputeHash(objectAsBytes);

        return byteArrayToHex(result);
    }
    catch (ArgumentNullException ane)
    {
        return null;
    }
}



private static byte[] ObjectToByteArray(Object objectToSerialize)
{            
    MemoryStream ms = new MemoryStream();
    //BinaryFormatter formatter = new BinaryFormatter();            
    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
    try
    {
        //Here's the core functionality! One Line!
        //To be thread-safe we lock the object
        lock (locker)
        {
            x.Serialize(ms, objectToSerialize);
            //formatter.Serialize(fs, objectToSerialize);
        }
        //return fs.ToArray();                
        return ms.ToArray();
    }
    catch (SerializationException se)
    {                
        return null;
    }
    finally
    {
        //fs.Close();
        ms.Close();
    }
}

}

You did not hash the UTF-8 representation of your string. You hashed the UTF-8 representation of your string's hashcode . That is:

  var bytes = utf8.encode(a.hashCode.toString());

should be just:

  var bytes = utf8.encode(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM