我用的chat js demo来尝试着做auth
但是我尝试好长时间之后都返回:[WebSocket] Fail connection by server: code=4102 reason=SIGNATURE_FAILED
我的关键代码如下:
chat = new AVChatClient({
appId: appid,
peerId: $('#sender').val() || 'testuser' + Math.random(),
watchingPeerIds: watching,
auth: auth//当网站设置开启签名的时候需要
});
我已经开启了auth函数
function auth(peerId, watchingPeers) {
return new Promise(function(resolve, reject) {
$.post('http://127.0.0.1/js-chat-sdk-samples/sign.php', {
self_id: peerId,
watch_ids: watchingPeers.join(':')
}).success(function(data) {
data = eval('(' + data + ')');
resolve({
n: data.nonce,
t: data.timestamp,
s: data.signature,
watchingPeerIds: data.watch_ids.split(':')
});
}).error(function(err) {
reject(err);
})
})
}
数据已经正确的进入到了php当中
$peer = $_POST['self_id'];
$wi = $_POST['watch_ids'];
$nonce = generate_Random_string(5);
$tmp=strtotime("-8 hour");//时间我检查了,确实是比北京时间提前8小时
$return["nonce"]=$nonce;
$return["timestamp"]=$tmp;
$return["signature"]=getSignature("i468qlm1fb110m02439xpqsa7sm0bqn6iezbmtyjm2tje0nc:$peer:$wi:$tmp:$nonce",我的masterkey);
$return["watch_ids"]=$wi;
程序返回类似:
{"nonce":"ZArK4","timestamp":1414137902,"signature":"5MIZyY4wXsK9Ka\/FvTXLnSsq5fI=","watch_ids":"2"}
我在php服务器上实现的Signature 工厂函数:
function getSignature($str, $key) {
$signature = "";
if (function_exists('hash_hmac')) {
$signature = base64_encode(hash_hmac("sha1", $str, $key, true));
} else {
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize) {
$key = pack('H*', $hashfunc($key));
}
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack(
'H*', $hashfunc(
($key ^ $opad) . pack(
'H*', $hashfunc(
($key ^ $ipad) . $str
)
)
)
);
$signature = base64_encode($hmac);
}
return $signature;
}
echo json_encode($return);
随机字符串函数实现:
function generate_Random_string( $length = 8 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //!@#$%^&*()-_ []{}<>~`+=,.;:/?|
$password = "";
for ( $i = 0; $i < $length; $i++ )
{
$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $password;
}
请各位大大帮我排查一下故障的位置。小弟感激不尽!
初步看首先是签名算法最后不需要base64,而是应该to hex string,你可以更新一下看看还有没有问题