PHP相当于C#加密库

时间:2018-01-24 04:11:36

标签: php cryptography

如何将以下C#转换为PHP?

string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)  
{  
    var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };  

    verb = verb ?? "";  
    resourceType = resourceType ?? "";
    resourceId = resourceId ?? "";

    string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",  
            verb.ToLowerInvariant(),  
            resourceType.ToLowerInvariant(),  
            resourceId,  
            date.ToLowerInvariant(),  
            ""  
    );  

    byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));  
    string signature = Convert.ToBase64String(hashPayLoad);  

    return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",  
        keyType,  
        tokenVersion,  
        signature));  
}  

或者,请让我知道相应的库。 谢谢。 Velu

1 个答案:

答案 0 :(得分:0)

我在其他地方找到了答案。发布在这里以防有人想要它。

private function getAuthHeaders($verb, $resource_type, $resource_id)
{
    $x_ms_date = gmdate('D, d M Y H:i:s T', strtotime('+2 minutes'));
    $master = 'master';
    $token = '1.0';
    $x_ms_version = '2017-02-22';

    $key = base64_decode($this->master_key);
    $string_to_sign = $verb . "\n" .
                      $resource_type . "\n" .
                      $resource_id . "\n" .
                      $x_ms_date . "\n" .
                      "\n";

    $sig = base64_encode(hash_hmac('sha256', strtolower($string_to_sign), $key, true));

    return Array(
             'Accept: application/json',
             'User-Agent: documentdb.php.sdk/1.0.0',
             'Cache-Control: no-cache',
             'x-ms-date: ' . $x_ms_date,
             'x-ms-version: ' . $x_ms_version,
             'authorization: ' . urlencode("type=$master&ver=$token&sig=$sig")
           );
}