Saikat
Saikat

Reputation: 1

php sha1 does not match .Net sha1Managed

I am having problem in matching a SHA1 algorithm in PHP and C# .Net. I need to modify the PHP code to match with .Net value.

The code in .Net is as following:

DateTime dtNow = DateTime.parse("4/29/2013 11:50:18 PM");
//Create the site token header
var siteTokenMessageHeader = new SiteTokenMessageHeader
{
    MessageId = "0289ED53-D69B-451C-BCBB-C7412D07AFFE",
    //Unquie Id per message, use for auditing
    TimeStamp = dtNow,
    //Current Time
    SiteId = _siteId,
};
//Construct Token 
var token = string.Format(
    "{0}:\"MessageId\":\"{1}\"\"SiteId\":\"{2}\"\"TimeStamp\":\"{3}\"",
    _siteKey,
    siteTokenMessageHeader.MessageId,
    siteTokenMessageHeader.SiteId,
    siteTokenMessageHeader.TimeStamp.ToString(new CultureInfo("en-US"))); //1/1/2000 12:00:00 AM
//Construct signature from token
var shaProvider = new SHA1Managed();
var rawKey = Encoding.Unicode.GetBytes(token);
var rawHash = shaProvider.ComputeHash(rawKey);
var signature = BitConverter.ToString(rawHash).Replace("-", "").ToLower();

siteTokenMessageHeader.SiteSignature = signature;

The signature variable value: 8cf9000e9b1a6da0e898bada5bf6dd8f6d17d72a

The PHP code is as following:

$str = $SiteKey.':"MessageId":"0289ED53-D69B-451C-BCBB-C7412D07AFFE""SiteId":"'.$SiteId.'""TimeStamp":"4/29/2013 11:50:18 AM"';
$hash = sha1($str);

The $hash variable value: 1d2fb85fd63a14de0b5e0a95be253eac1a625128

The same topic has been answered quite a few times but none of those are helpful in this case. Anybody's help will be appreciable.

Upvotes: 0

Views: 833

Answers (2)

CodesInChaos
CodesInChaos

Reputation: 108790

There are several issues:

  1. As @Yogesh notes, the string is different (AM vs. PM)
  2. The C# code uses UTF-16, the php code ASCII or some legacy encoding
  3. Your MAC construction is broken. SHA-1(key||message) is vulnerable to length extension attacks.

Since the code is broken, you need to change it on both sides. I recommend switching to HMAC-SHA-2 with a UTF-8 encoded message.

Upvotes: 1

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

See here its AM in PHP

""TimeStamp":"4/29/2013 11:50:18 AM"'
                                 ^^

And PM in C#

parse("4/29/2013 11:50:18 PM");
                          ^^

Because of this ,different result is coming.

Make both as AM OR PM, you will get same hash.

Upvotes: 1

Related Questions