我必须在dart中将字符串转换为sha256。例如,我使用 String a =“ 2424242401224672”; 在下面的代码中,结果为:摘要: 7b73641404a8fe6a4b1161a85db736be2a6c07a046109b993186f7a22190bf13
代码:
String a = "2424242401224672";
var bytes = utf8.encode(a.hashCode.toString());
var digest = sha256.convert(bytes);
print("digest: $digest");
在另一方中,将c#用于sha256。他们使用c#MemoryStream,BinaryFormatter和XMLSerilizer从字符串(对象)获取字节。
但是当我显示结果时,他们告诉我在C#sha256中得到不同的结果吗?
如何使用Dart sha256和C#sha256获得相同的结果?
更新:
CSharp中的字符串“ 2424242401224672”的sha256值为: DE4841A9E623AF7D5C598A67C2461702485F6B77C3EB5448FA5E0DDF074C70D8
更新2:
csharp代码:
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();
}
}
}
答案 0 :(得分:1)
您没有哈希字符串的UTF-8表示形式。您对字符串的 hashcode 的UTF-8表示进行了哈希处理。那就是:
var bytes = utf8.encode(a.hashCode.toString());
应该只是:
var bytes = utf8.encode(a);