使用hash_hmac将php移植到C#时出现问题

时间:2014-07-21 20:07:32

标签: c# php hash porting translate

我正在尝试将脚本从php移植到C#。该脚本是为我的学校内部网创建一个密钥进行身份验证。我得到了大部分,但两者的输出不同。

PHP代码:

/**
 * Generate authorization headers
 *
 * @param string $username
 * @param string $password
 * @param string $prefix
 * @param string $hashAlgorithm
 *
 * @return array(
 *          'X-gr-AuthDate': uncrypted date
 *          'Authorization': encrypted token
 * )
 */

function generateHeaders($username, $password, $prefix, $hashAlgorithm = 'sha1')
{
    $rfc_1123_date = gmdate('D, d M Y H:i:s T', time());
    $xgrdate = utf8_encode($rfc_1123_date);
    $userPasswd = base64_encode(hash($hashAlgorithm, $password, true));

    $signature = base64_encode(hash_hmac($hashAlgorithm, $userPasswd, $xgrdate));
    $auth = $prefix . " " . base64_encode($username) . ":" . $signature;
    $headers = array(
                   'X-gr-AuthDate' => $xgrdate,
                   'Authorization' => $auth
    );

    return $headers;
}

$headers = generateHeaders("rest-example", "topsecret", "gr001");

header('Content-Type: application/json');

echo json_encode($headers);

C#中的代码:

    public static void Main (string[] args)
    {
        // Get data from php function
        WebClient wc = new WebClient ();
        byte[] res = wc.DownloadData ("http://localhost/test.php");
        JObject obj = JObject.Parse (System.Text.Encoding.UTF8.GetString (res));
        Console.WriteLine ((string)obj["Authorization"]);

        // Generate auth data
        string[] test = ConstructHeaders ("rest-example", "topsecret", "gr001");
        Console.WriteLine (test [0]);
    }

    public static string[] ConstructHeaders(string username, string password, string prefix)
    {
        Encoding utf8 = Encoding.UTF8;
        SHA1 sha = new SHA1CryptoServiceProvider(); 

        // Get current date
        DateTime now = DateTime.Now;
        string rfc_date = now.ToString ("ddd, dd MMM yyyy HH:mm:ss") + " GMT"; // TODO: Automatically add timezone


        string userPasswd = Convert.ToBase64String(sha.ComputeHash (utf8.GetBytes(password)));
        string signature = Convert.ToBase64String(utf8.GetBytes(EncodeHMac (userPasswd, rfc_date)));

        string auth = prefix + " " +  Convert.ToBase64String(utf8.GetBytes(username)) + ":" + signature;
        return new string[] {auth, rfc_date};
    }

    static string EncodeHMac(string message, string key)
    {
        var keyByte = Encoding.UTF8.GetBytes(key);
        using (var hmacsha1 = new HMACSHA1(keyByte))
        {
            hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(message));

            return ByteToString(hmacsha1.Hash);
        }
    }
    static string ByteToString(byte[] buff)
    {
        string sbinary = "";
        for (int i = 0; i < buff.Length; i++)
            sbinary += buff[i].ToString("X2"); /* hex format */
        return sbinary;
    }

输出产生例如:

gr001 cmVzdC1leGFtcGxl:NmY4ZTgzMWI4NGRhYmExYTEzMjdmMzQ3Nzg3ZWU0MDNjZWQ1ZTFhOQ==
gr001 cmVzdC1leGFtcGxl:MTUzMzlEMTQyNjRBNzZEQ0I2QkJERUE4MjEyMkNCQ0Q4ODhCQjE2MQ==

第一个(正确的)与C#中的第二个不匹配。 到目前为止我调试的是userPasswd是正确生成的,但是当我到达hmac散列部分时它就不再匹配了。

此外,我从文档中得到了所有内容:

X-gr-AuthDate: date
Authorization: prefix encoded_username:signature



where

    date = according to RFC 822, updated by RFC 1123, e.g 'Sun, 06 Nov 1994 08:49:37 GMT'
    prefix = gr001 (provided with your account's security credentials)
    encoded_username = Base64(username)
    signature = Base64(HMAC-Sha1(secret-token, date))



    where

        secret-token = hash(user-password), hash function to use is provided with your account's security credentials (SHA-1)

1 个答案:

答案 0 :(得分:0)

我明白了!

我犯了两个错误:

  1. 我使用DateTime.Now代替DateTime.UtcNow所以日期为。{1}} 这两个功能不匹配。 (我不知道我怎么错过了......)

  2. 虽然php中的hash_hmac函数将十六进制字符串作为小写返回,但C#函数以大写形式返回,因此我在Convert.ToBase64String

  3. 中得到了不同的结果

    感谢您的帮助。