如何在PHP单元测试中获得相同的HMAC256结果? [英] How can I get the same HMAC256-results in C# like in the PHP unit tests?

查看:174
本文介绍了如何在PHP单元测试中获得相同的HMAC256结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我会尝试,并获得新的签名请求逻辑添加到我的Facebook画布应用程序,让这个简单自己我去了GitHub上的PHP PHP sdk,并看看单元测试

I thought I would try and get the new Signed Request logic added to my facebook canvas application, to make this "easy" on myself I went to the facebook PHP sdk over at GitHub and took a look at the unit tests.

我的实际问题是,我无法获取包含在请求中匹配我使用应用程序秘密计算的哈希值和请求中发送的数据的哈希值。

My actual problem is that I cannot get the hash included in the request to match the hash I calculate using the application secret, and the data sent within the request.

这是如何工作的描述在 Facebook的身份验证页面

How this is meant to work is described at Facebook's authentication page.

private string VALID_SIGNED_REQUEST = "ZcZocIFknCpcTLhwsRwwH5nL6oq7OmKWJx41xRTi59E.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOiIxMjczMzU5NjAwIiwib2F1dGhfdG9rZW4iOiIyNTQ3NTIwNzMxNTJ8Mi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODV8dUk3R3dybUJVZWQ4c2VaWjA1SmJkekdGVXBrLiIsInNlc3Npb25fa2V5IjoiMi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODUiLCJ1c2VyX2lkIjoiMTY3Nzg0NjM4NSJ9";

private string NON_TOSSED_SIGNED_REQUEST = "laEjO-az9kzgFOUldy1G7EyaP6tMQEsbFIDrB1RUamE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiJ9";

public void SignedRequestExample()
{
 var Encoding = new UTF8Encoding();

 string ApplicationSecret = "904270b68a2cc3d54485323652da4d14"; 

 string SignedRequest = VALID_SIGNED_REQUEST;
 string ExpectedSignature = SignedRequest.Substring(0, SignedRequest.IndexOf('.'));
 string Payload = SignedRequest.Substring(SignedRequest.IndexOf('.') + 1);

 // Back & Forth with Signature
 byte[] ActualSignature = FromUrlBase64String(ExpectedSignature);
 string TestSignature = ToUrlBase64String(ActualSignature);

 // Back & Forth With Data
 byte[] ActualPayload = FromUrlBase64String(Payload);
 string Json = Encoding.GetString(ActualPayload);
 string TestPayload = ToUrlBase64String(ActualPayload);

 // Attempt to get same hash
 var Hmac = SignWithHMAC(ActualPayload, Encoding.GetBytes(ApplicationSecret));
 var HmacBase64 = ToUrlBase64String(Hmac);            
 var HmacHex = BytesToHex(Hmac);

 if (HmacBase64 != ExpectedSignature)
 {
  // YAY
 }
 else
 {
  // BOO
 }
}

private static string BytesToHex(byte[] input)
{
 StringBuilder sb = new StringBuilder();

 foreach (byte b in input)
 {
  sb.Append(string.Format("{0:x2}", b));
 }
 return sb.ToString();
}
private string ToUrlBase64String(byte[] Input)
{
 return Convert.ToBase64String(Input).Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
}

// http://tools.ietf.org/html/rfc4648#section-5            
private byte[] FromUrlBase64String(string Base64UrlSafe)
{
 Base64UrlSafe = Base64UrlSafe.PadRight(Base64UrlSafe.Length + (4 - Base64UrlSafe.Length % 4) % 4, '=');
 Base64UrlSafe = Base64UrlSafe.Replace('-', '+').Replace('_', '/');
 return Convert.FromBase64String(Base64UrlSafe);
}

private byte[] SignWithHMAC(byte[] dataToSign, byte[] keyBody)
{
 using (var hmac = new HMACSHA256(keyBody))
 {
  hmac.ComputeHash(dataToSign);
  /*
  CryptoStream cs = new CryptoStream(System.IO.Stream.Null, hmac, CryptoStreamMode.Write);
  cs.Write(dataToSign, 0, dataToSign.Length);
  cs.Flush();
  cs.Close();
  byte[] hashResult = hmac.Hash;
  */
  return hmac.Hash;
 }
}

public string Base64ToHex(string input)
{
 StringBuilder sb = new StringBuilder();
 byte[] inputBytes = Convert.FromBase64String(input);
 foreach (byte b in inputBytes)
 {
  sb.Append(string.Format("{0:x2}", b));
 }
 return sb.ToString();
}

回答谢谢下面的Rasmus,协助任何人在这里是更新达代码):

Answer thanks to Rasmus below, to assist anyone else here is the updated (cleaned up code):

/// Example signed_request variable from PHPSDK Unit Testing
private string VALID_SIGNED_REQUEST = "ZcZocIFknCpcTLhwsRwwH5nL6oq7OmKWJx41xRTi59E.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOiIxMjczMzU5NjAwIiwib2F1dGhfdG9rZW4iOiIyNTQ3NTIwNzMxNTJ8Mi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODV8dUk3R3dybUJVZWQ4c2VaWjA1SmJkekdGVXBrLiIsInNlc3Npb25fa2V5IjoiMi5JX2VURmtjVEtTelg1bm8zakk0cjFRX18uMzYwMC4xMjczMzU5NjAwLTE2Nzc4NDYzODUiLCJ1c2VyX2lkIjoiMTY3Nzg0NjM4NSJ9";

public bool ValidateSignedRequest()
{            
    string applicationSecret = "904270b68a2cc3d54485323652da4d14";
    string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');            
    string expectedSignature = signedRequest[0];
    string payload = signedRequest[1];

    // Attempt to get same hash
    var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
    var HmacBase64 = ToUrlBase64String(Hmac);

    return (HmacBase64 == expectedSignature);           
}


private string ToUrlBase64String(byte[] Input)
{
    return Convert.ToBase64String(Input).Replace("=", String.Empty)
                                        .Replace('+', '-')
                                        .Replace('/', '_');
}

private byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
{
    using (var hmacAlgorithm = new HMACSHA256(keyBody))
    {
        hmacAlgorithm.ComputeHash(dataToSign);
        return hmacAlgorithm.Hash;
    }
}


推荐答案

不应该在计算HMAC之前对有效负载进行base64解码。

You are not supposed to base64-decode the payload before calculating the HMAC.

使用此行:

var Hmac = SignWithHMAC(Encoding.GetBytes(Payload), Encoding.GetBytes(ApplicationSecret));

它应该可以工作。

几个更多的指针:


  • 而不是使用 Substring() IndexOf()尝试使用 String.Split()

  • 您已切换YAY和BOO注释

  • 如果你遵循以小写开始局部变量的名称的通用规则,C#代码是更可读的(像这样: var applicationSecret =...;

  • Instead of fiddling with Substring() and IndexOf() try using String.Split()
  • You have switched the YAY and BOO comments around
  • C# code is more readable if you follow the common rule of starting the names of local variables with lowercase (like this: var applicationSecret = "...";)

这篇关于如何在PHP单元测试中获得相同的HMAC256结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆