crypto icon indicating copy to clipboard operation
crypto copied to clipboard

Why Dart sha256 and Csharp sha256 has different result?

Open NTMS2017 opened this issue 6 years ago • 7 comments

I have dart code that converts string to sha256 hash. remarry party using csharp and same string they get different result.

So where should I have to look? What should I tell them?

Why Dart sha256 and Csharp sha256 has different result?

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

NTMS2017 avatar Apr 22 '19 12:04 NTMS2017

@NTMS2017 can I see an example for C#?

listepo avatar Aug 06 '19 18:08 listepo

I have been investigating this, as now I also have an issue with it.

I've noticed that in the previous version of Dart, the calculation of sha256 was plain wrong. I guess it was related to https://github.com/dart-lang/sdk/issues/37551.

With the new version of dart, the issue has been resolved and I see the same results on all platforms now.

jeroentrappers avatar Sep 26 '19 08:09 jeroentrappers

Same here, but with java...

I get same byte list in dart and java [0, -70, -39, 127, -7, 73, -103, -21, 58, -74, -28, 92, 69, -110, -32, -36, 91, -79, 40, -90, 88]

But when I apply sha256 in java I get [-21, 39, 73, 31, 62, 75, -91, 44, 65, 19, 47, -62, 25, 84, -63, 20, 78, 29, -118, 38, -31, -55, -73, 49, 113, 86, 51, 108, -51, 95, 84, -94] Using this code:

byte[] hash1 = sha256(Arrays.copyOfRange(decoded, 0, 21)); private static byte[] sha256(byte[] data) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(data); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } }

I dart I get: [235, 39, 73, 31, 62, 75, 165, 44, 65, 19, 47, 194, 25, 84, 193, 20, 78, 29, 138, 38, 225, 201, 183, 49, 113, 86, 51, 108, 205, 95, 84, 162] Using: List hash1 = sha256.convert(temp.sublist(0, 21)).bytes;

xellDart avatar Nov 07 '19 05:11 xellDart

I'm having the same issues. Actually I'm calculating multiple hashes and it seems that for one of them I'm always encountering this issue. Has anyone been able to work around this issue? It's quite a critical one for me.

michaelgobbers avatar Dec 27 '19 16:12 michaelgobbers

Have u tried updating your Dart sdk like @xellDart advised?

as1ndu avatar Dec 30 '19 21:12 as1ndu

The byte data type in java is an 8-bit signed integer. It has a minimum value of -128 and a maximum value of 127. In dart the Digest use unsigned 8-bit integer rather than signed , which has a minimum value of 0 and a maximum value of 255, but actually they represent the same thing.

licy183 avatar Aug 26 '20 16:08 licy183

hi bro how to slove it?

WeJeson avatar Oct 31 '22 09:10 WeJeson