Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hey guys,

Is there any method in c# that would output the same result as the php sha1().

http://se2.php.net/manual/en/function.sha1.php[^]

I am using the follwing code but the hash differs with the one created with php's sha1().

C#
namespace sha1
{
    class toSha1
    {
        public string Sha1Sum(string strToEncrypt)
        {
            UTF8Encoding ue = new UTF8Encoding();
            byte[] bytes = ue.GetBytes(strToEncrypt);

            // encrypt bytes
            SHA1 sha = new SHA1CryptoServiceProvider();
            byte[] hashBytes = sha.ComputeHash(bytes);

            // Convert the encrypted bytes back to a string (base 16)
            string hashString = "";

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
            }

            return hashString.PadLeft(32, '0');
        }
    }
}
Posted

1 solution

The first thing to do is to check that you are providing exactly the same input: Instead of doing a string-to-bytes conversion in C#, via UTF8, set up an array of known byte values and feed it to both systems.

If the outputs are still different, compare them for length. If they are not the same, them you need to look at the actual output and decide what each function is actually generating, as the SHA1 hash value is a very specific number of bits long - 160 - but there are longer variants up to 1024 bits in the pipeline and I generally use 512 bit SHA values for secure systems.

You will probably find that one output is packed into 20 bytes, and the other is encoded as a string of 40 hexadecimal characters.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900