<?php namespace utils; /** * */ class Jwt { public $KEY = 'hao'; /** * [返回 hash 加密后的字符串] * @param [type] $header [description] * @param [type] $payload [description] * @return [type] [description] */ private function hash_do($str, $type){ $algo = 'sha256'; if (strtoupper($type) == 'MD5'){ $algo = 'md5'; } else if(strtolower($type) == 'HAVAL'){ $algo = 'haval160,4'; } return hash($algo, $str); } /** * [create_token description] * @param [type] $header [description] * @param [type] $payload [description] * @return [type] [description] */ public function create_token($header, $payload){ if (!empty($header) && is_array($header) && (strtoupper($header['alg'])=='HS256' || strtoupper($header['alg'])=='MD5' || strtoupper($header['alg'])=='HAVAL') && !empty($payload)) { $h = base64_encode(json_encode($header)); $p = base64_encode(json_encode($payload)); $s = $this->hash_do($h . $p . md5($this->KEY), $header['alg']); $sign = $h. '.' . $p . '.' . $s; return $sign; } return null; } public function check_token($jwt){ if (empty($jwt)){ return false; } $tokens = explode('.', $jwt); if (count($tokens)!==3){ return false; } list($header64, $payload64, $sign) = $tokens; $header = json_decode(base64_decode($header64), TRUE); if (!isset($header['alg'])){ return false; } $s = $this->hash_do($header64 . $payload64 . md5($this->KEY), $header['alg']); if ($s !== $sign){ return false; } $payload = json_decode(base64_decode($payload64), TRUE); $time = time(); if (isset($payload['iat']) && $payload['iat'] > $time){ return false; } if (isset($payload['exp']) && $payload['exp'] < $time){ return false; } return true; } }
使用方式:
public function auth_token(){ $over = config('TOKEN_OVER_TIME'); // 生存时间 $time = time(); $time_over = $time + $over; $header = [ 'typ' => 'JWT', 'alg' => 'HS256' ]; $payload = [ 'iss' => 'admin_name', 'iat' => $time, 'exp' => $time_over, 'uid' => 12 ]; $j = new Jwt(); $sign = $j->create_token($header, $payload); return $sign; } public function check(){ $jwt = 'jwtxxxxxxxx'; $j = new Jwt(); $b = $j->check_token($jwt); dump($b); }