Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); 
like image 772
Anand Capur Avatar asked Apr 26 '09 04:04

Anand Capur


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

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

like image 167
Andrew Moore Avatar answered Oct 10 '22 15:10

Andrew Moore


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"))); } 
like image 45
OmarElsherif Avatar answered Oct 10 '22 16:10

OmarElsherif