FetFrumos
FetFrumos

Reputation: 5964

SHA1(c#) - different result from .Net 3 and .Net Core

I have hash value in database. This was created in Asp Web Form (probably .Net 3). This is old code:

string hash = SHA1(SHA1(pass.Trim() + number.Trim()));

These are examples of data:

 pass = AGent24022 
 number = 24022
 hash = 2cdfaec91e938eaa7f432fd606745c23399cc3b8

I need to generate this hash from this data in Asp Net Core. But I cannot get this value. These are examples of some of my implementations.

 //1
    static string Hash2(string input)
    {
      return string.Join("",SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(input)).Select(x => 
     x.ToString("x2")));
    }
 
       //2
     static string Hash1(string input){ 
      using (var sha1 = new SHA1Managed())
      {
           return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(input)));
      }
    }

        //3
        static string Hash0(string input)
        {
            var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
            return string.Concat(hash.Select(b => b.ToString("x2")));
        }

This is my use:

 string input = pass.Trim() + number.Trim();
 var res = Hash0(Hash0(input);
 //var res = Hash1(Hash1(input);
 //var res = Hash2(Hash2(input);
 

Perhaps the reason is a change in implementation. Any advice, I would be very grateful.

Upvotes: 3

Views: 1626

Answers (1)

BenM
BenM

Reputation: 529

.NET strings are UTF-16 by default, so that's what would have been used in the old implementation.

If you take your Hash2 implementation and change Encoding.UTF8 to Encoding.Unicode (which encodes to UTF-16), then it should work.

class Program
{
    static string Hash(string input)
    {
        using (var sha1 = new SHA1Managed())
        {
            return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.Unicode.GetBytes(input)).Select(x => x.ToString("x2")));
        }
    }

    static void Main(string[] args)
    {
        var result = Hash(Hash("AGent2402224022"));
        Console.Write(result); // outputs "2cdfaec91e938eaa7f432fd606745c23399cc3b8"
    }
}

Upvotes: 4

Related Questions