C# SHA-1 vs. PHP SHA-1...Different Results?

19,234

Solution 1

Use ASCIIEncoding instead of UnicodeEncoding. PHP uses ASCII charset for hash calculations.

Solution 2

This method in .NET is equivalent to sha1 in php:

string sha1Hash(string password)
{
    return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("x2")));
}

Solution 3

I had this problem also. The following code will work.

string dataString = "string to hash";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string localChecksum = BitConverter.ToString(hashBytes)
.Replace("-", "").ToLowerInvariant();

Solution 4

Had the same problem. This code worked for me:

string encode = secretkey + email;
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
byte[] encodeBytes = Encoding.ASCII.GetBytes(encode);
byte[] encodeHashedBytes = sha1.ComputeHash(passwordBytes);
string pencodeHashed = BitConverter.
ToString(encode HashedBytes).Replace("-", "").ToLowerInvariant();

Solution 5

FWIW, I had a similar issue in Java. It turned out that I had to use "UTF-8" encoding to produce the same SHA1 hashes in Java as the sha1 function produces in PHP 5.3.1 (running on XAMPP Vista).

    private static String SHA1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("UTF-8"));
        return new String(org.apache.commons.codec.binary.Hex.encodeHex(md.digest()));
    }
Share:
19,234
Rita Zhang
Author by

Rita Zhang

I'm an entrepreneur, programmer, and sysadmin. My interests are mainly focused in SaaS/Web Apps.

Updated on June 27, 2022

Comments

  • Rita Zhang
    Rita Zhang about 2 years

    I am trying to calculate a SHA-1 Hash from a string, but when I calculate the string using php's sha1 function I get something different than when I try it in C#. I need C# to calculate the same string as PHP (since the string from php is calculated by a 3rd party that I cannot modify). How can I get C# to generate the same hash as PHP? Thanks!!!

    String = [email protected]

    C# Code (Generates d32954053ee93985f5c3ca2583145668bb7ade86)

            string encode = secretkey + email;
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] HashValue, MessageBytes = UE.GetBytes(encode);
            SHA1Managed SHhash = new SHA1Managed();
            string strHex = "";
    
            HashValue = SHhash.ComputeHash(MessageBytes);
            foreach(byte b in HashValue) {
                strHex += String.Format("{0:x2}", b);
            }
    

    PHP Code (Generates a9410edeaf75222d7b576c1b23ca0a9af0dffa98)

    sha1();