Sha1cryptoserviceprovider and Sha1managed return different results

Asked

Viewed 65 times

3

I need to encrypt a string using SHA1. I was able to encrypt using the SHA1 class in this way:

 public string CriptSha1(string secret)
        {

            string result = "";

            byte[] key = System.Text.Encoding.UTF8.GetBytes(secret);

            SHA1 sha1 = SHA1Managed.Create();

            byte[] hash = sha1.ComputeHash(key);

            foreach (byte b in hash)
            {
                result += b.ToString();
            }

            return result;
        }

If you happen to encrypt the word teste the way out is:

4611115513881331821151451031201166997127855811595

Now if I encrypt using the Sha1cryptoserviceprovider class like this:

SHA1CryptoServiceProvider cryptTransformSHA1 = new SHA1CryptoServiceProvider();

byte[] buffer = Encoding.UTF8.GetBytes(secret);
string hashSecret = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-","");

The way out is:

2E6F9B0D5885B6010F91677845617F553A735F

Can anyone tell me why? or what is the difference between these classes ?

  • I found that what makes the output different is Bitconverter but after all what is the most suitable way to encrypt in SHA1 use Bitconverter or just use a Tostring() ?

1 answer

0

Your first code is incomplete, just returns the bytes and is not converting them.

That line:

result += b.ToString();

You should turn to hexadecimal, like this:

result += b.ToString("X2");

2E6F9B0D5885B6010F91677845617F553A735F

Ideone Exemplo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.