Cabuxa.Mapache
Cabuxa.Mapache

Reputation: 771

Different results generating SHA256 hash with .Net and react native library (same input)

In .Net I'm generating a hash this way:

Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes("123456")));

The result is: "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI="

Now I'm generating a hash in a React Native app with this library:

import { sha256 } from 'react-native-sha256';
return await sha256('123456');

And the result is: "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"

Not sure what I'm doing wrong...

EDIT:

Final solution (thanks Martin Backasch):

var inputBytes = Encoding.UTF8.GetBytes("123456");
var hashBytes = SHA256.Create().ComputeHash(inputBytes);
return BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower();

Upvotes: 1

Views: 1498

Answers (1)

Martin Backasch
Martin Backasch

Reputation: 1899

The result from the library is HEX. You have to convert it to Base64

Try it here.

Input:

"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"

Output:

"jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI="

You can convert your C# result from Base64 to HEX by using the example given by microsoft or as a quick snippet:

var yourResult = Convert.ToBase64String(SHA256.Create()
                                              .ComputeHash(Encoding.UTF8
                                                                   .GetBytes("123456")));

var apiResult = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";

var yourHexResult = BitConverter.ToString(Convert.FromBase64String(yourResult))
                                .Replace("-", string.Empty)
                                .ToLower();

Debug.Assert(yourHexResult == apiResult, "yourHexResult != apiResult");

Upvotes: 3

Related Questions