数据令牌的传递的生成、验证和解析

<?php

function base64UrlDecode($input)
{
	return base64_decode(strtr($input, '-_', '+/'));
}
function base64UrlEncode($input)
{
	return base64_encode(strtr($input, '+/', '-_'));
}

// 生成令牌
function parseSignedRequest($signed_request, $secret='4f5fcdc6514f7ee25ec4fa7c7853e8e1') 
{
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

	// decode the data
    $sig = base64UrlDecode($encoded_sig);
    $data = json_decode(base64UrlDecode($payload), true);

    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') 
	{
      die('Unknown algorithm. Expected HMAC-SHA256');
      return null;
    }

    // check sig
    $expected_sig = hash_hmac('sha256', $payload,$secret, $raw = true);
    if ($sig !== $expected_sig) 
	{
      die('Bad Signed JSON signature!');
      return null;
    }

    return $data;
}

// 解析
function generateSignature($info,$secret='4f5fcdc6514f7ee25ec4fa7c7853e8e1')
{
	$body = base64UrlEncode(json_encode(($info)));
	$sign = hash_hmac('sha256', $body,$secret,true);

	$signed_request = base64UrlEncode($sign) . "." . $body;

	return $signed_request;
}

$info = array(
	'algorithm'=> 'HMAC-SHA256',
	"userId" => 'aaa',
	'userName' => 'asdsad',
	'sex' => '1'
);

print_R(parseSignedRequest(generateSignature($info)));

?>

你可能感兴趣的:(json,PHP)