auth_digest.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. require_once("utils.php");
  3. require_once("conf.php");
  4. // ----------------------------------------------------------
  5. class Qiniu_Mac {
  6. public $AccessKey;
  7. public $SecretKey;
  8. public function __construct($accessKey, $secretKey)
  9. {
  10. $this->AccessKey = $accessKey;
  11. $this->SecretKey = $secretKey;
  12. }
  13. public function Sign($data) // => $token
  14. {
  15. $sign = hash_hmac('sha1', $data, $this->SecretKey, true);
  16. return $this->AccessKey . ':' . Qiniu_Encode($sign);
  17. }
  18. public function SignWithData($data) // => $token
  19. {
  20. $data = Qiniu_Encode($data);
  21. return $this->Sign($data) . ':' . $data;
  22. }
  23. public function SignRequest($req, $incbody) // => ($token, $error)
  24. {
  25. $url = $req->URL;
  26. $url = parse_url($url['path']);
  27. $data = '';
  28. if (isset($url['path'])) {
  29. $data = $url['path'];
  30. }
  31. if (isset($url['query'])) {
  32. $data .= '?' . $url['query'];
  33. }
  34. $data .= "\n";
  35. if ($incbody) {
  36. $data .= $req->Body;
  37. }
  38. return $this->Sign($data);
  39. }
  40. public function VerifyCallback($auth, $url, $body) // ==> bool
  41. {
  42. $url = parse_url($url);
  43. $data = '';
  44. if (isset($url['path'])) {
  45. $data = $url['path'];
  46. }
  47. if (isset($url['query'])) {
  48. $data .= '?' . $url['query'];
  49. }
  50. $data .= "\n";
  51. $data .= $body;
  52. $token = 'QBox ' . $this->Sign($data);
  53. return $auth === $token;
  54. }
  55. }
  56. function Qiniu_SetKeys($accessKey, $secretKey)
  57. {
  58. global $QINIU_ACCESS_KEY;
  59. global $QINIU_SECRET_KEY;
  60. $QINIU_ACCESS_KEY = $accessKey;
  61. $QINIU_SECRET_KEY = $secretKey;
  62. }
  63. function Qiniu_RequireMac($mac) // => $mac
  64. {
  65. if (isset($mac)) {
  66. return $mac;
  67. }
  68. global $QINIU_ACCESS_KEY;
  69. global $QINIU_SECRET_KEY;
  70. return new Qiniu_Mac($QINIU_ACCESS_KEY, $QINIU_SECRET_KEY);
  71. }
  72. function Qiniu_Sign($mac, $data) // => $token
  73. {
  74. return Qiniu_RequireMac($mac)->Sign($data);
  75. }
  76. function Qiniu_SignWithData($mac, $data) // => $token
  77. {
  78. return Qiniu_RequireMac($mac)->SignWithData($data);
  79. }
  80. // ----------------------------------------------------------