hash_hmac с 3-мя параметрами в php, эквивалентный csharp, javascript

ОПИСАНИЕ:

Кажется, я не могу понять, как PHP производит следующее:

echo hash_hmac("sha1", "what is this", true);
echo PHP_EOL; // end of line
echo base64_encode(hash_hmac("sha1", "what is this", true));

Ссылка для просмотра результатов онлайн (требуется копирование / вставка).

Как сказано в документации, вам нужны данные и ключ с правильным выводом, чтобы создать хэш SHA1 HMAC.

string hash_hmac(string $algo, string $data, string $key [, bool $raw_output = false])

Я хочу создать точный вывод с помощью csharp и javascript.


ПЫТАЛСЯ:

Это нормально, когда у меня есть данные и ключ, и я могу создать один и тот же хэш SHA1 HMAC для csharp и javascript.

// PHP
echo base64_encode(hash_hmac("sha1", "data", "key", true));

Ссылка для просмотра результатов онлайн (требуется копирование / вставка).

// CSharp
public static void Main(string[] args)
{
    Console.WriteLine(CreatePhpSha1HmacHash("data", "key"));
}

public static string CreatePhpSha1HmacHash(string data, string key)
{
    if (data == null)
    {
        data = string.Empty;
    }

    var encoding = new System.Text.UTF8Encoding(); // It's UTF-8 for my example

    var keyBytes = encoding.GetBytes(key);
    var dataBytes = encoding.GetBytes(data);

    using (var hmac = new System.Security.Cryptography.HMACSHA1(keyBytes))
    {
        var hash = hmac.ComputeHash(dataBytes);

        return Convert.ToBase64String(hash);
    }
}

Ссылка для просмотра результатов онлайн (требуется копирование / вставка).

// Javascript
var hash = CryptoJS.HmacSHA1('data', 'key');
var base64 = CryptoJS.enc.Base64.stringify(hash);

console.log('Sha1 hmac hash: ' + base64);

Ссылка для просмотра результатов онлайн.


ВОПРОС:

Как я могу создать точный вывод, как пример php, показанный в описании, когда он не использует два обязательных параметра? Может кто-нибудь объяснить мне, что делает php в этом случае?


ОТВЕТ:

@GentlemanMax: PHP внутренне приведёт TRUE к STRING, поэтому KEY будет преобразован в "1" как строковое значение. Когда raw_output установлен в TRUE, он выводит необработанные двоичные данные. FALSE выводит строчные буквы


РЕШЕНИЕ:

// CSharp
public static void Main(string[] args)
{
    // echo base64_encode(hash_hmac("sha1", "what is this", true));
    // echo base64_encode(hash_hmac("sha1", "what is this", true, false));
    Console.WriteLine(ToBase64EncodedHmacSha1("what is this", "1", false));
    Console.WriteLine(ToBase64EncodedHmacSha1("what is this", "1", false.ToString()));

    // echo base64_encode(hash_hmac("sha1", "what is this", true, true));
    Console.WriteLine(ToBase64EncodedHmacSha1("what is this", "1", true));
    Console.WriteLine(ToBase64EncodedHmacSha1("what is this", "1", true.ToString()));
}

public static string ToBase64EncodedHmacSha1(string data, string key, bool rawOutput = false)
{
    bool result;

    if (bool.TryParse(key, out result))
    {
        key = result ? 1.ToString() : 0.ToString();
    }

    var keyBytes = Encoding.UTF8.GetBytes(key);
    var dataBytes = Encoding.UTF8.GetBytes(data);

    using (var hmac = new HMACSHA1(keyBytes))
    {
        var hash = hmac.ComputeHash(dataBytes);

        if (rawOutput)
        {
            // output: raw binary
            return Convert.ToBase64String(hash);
        }

        // Convert an array of bytes to a string of hex digits.
        var hex = string.Concat(hash.Select(x => x.ToString("x2").ToLower()));

        var hexBytes = Encoding.UTF8.GetBytes(hex);

        // output: lowercase hexits
        return Convert.ToBase64String(hexBytes);
    }
}

Ссылка для просмотра результатов онлайн (требуется копирование / вставка).


// Javascript 
function toBase64EncodedHmacSha1(data, key, rawOutput) {
    // if boolean, cast to string
    if (typeof(key) === 'boolean') {
        key = key ? '1' : '0';
    }

    // optional
    if (typeof(rawOutput) === 'undefined') {
        rawOutput = false;
    }

    // check type
    if (typeof(rawOutput) !== 'boolean') {
        throw new Error('Raw output is Boolean value: true/false');
    }

    var hash = CryptoJS.HmacSHA1(data, key);

    if (rawOutput) {
        // output: raw binary
        return CryptoJS.enc.Base64.stringify(hash);
    }

    var hex = CryptoJS.enc.Hex.stringify(hash);
    var wordArray = CryptoJS.enc.Utf8.parse(hex);

    // output: lowercase hexits
    return CryptoJS.enc.Base64.stringify(wordArray);
}

// echo base64_encode(hash_hmac("sha1", "what is this", true));
// echo base64_encode(hash_hmac("sha1", "what is this", true, false));
console.log(toBase64EncodedHmacSha1('what is this', true));
console.log(toBase64EncodedHmacSha1('what is this', true, false));

// echo base64_encode(hash_hmac("sha1", "what is this", true, true));
console.log(toBase64EncodedHmacSha1('what is this', true, true));

console.log(toBase64EncodedHmacSha1('what is this', true, 'This will throw error'));

Ссылка для просмотра результатов онлайн.

1 ответ

Решение

Ключевым выводом здесь является то, что PHP будет внутренне приведен true в строку. В php, true бросает в "1" так

hash_hmac("sha1", "data", true);

Точно эквивалентно

hash_hmac("sha1", "data", "1")

Если вы не передадите 4-й параметр hash_hmac затем выводит хеш в шестнадцатеричном виде. Что не то, что вы делаете в вашем C# или JavaScript. Вот некоторые эквиваленты для работы с вами:

//PHP
hash_hmac("sha1", "data", true)

будет выводить так же, как

//JS
var hash = CryptoJS.HmacSHA1('data', "1")
console.log ( CryptoJS.enc.Hex.stringify(hash) ); //Note .Hex instead of .Base64

Так же,

//PHP
base64_encode(hash_hmac("sha1", "data", true, true));

так же, как делать

//JS
var hash = CryptoJS.HmacSHA1('data', "1")
console.log ( CryptoJS.enc.Base64.stringify(hash) );

Кроме того, PHP будет пытаться привести все не строковые значения для $key быть строкой. Вы всегда можете проверить, что происходит, позвонив по телефону strval($key) чтобы увидеть, что вы на самом деле используете для ключа.

Другие вопросы по тегам