digest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. require_once("utils.php");
  3. require_once("conf.php");
  4. define("NO_AUTH_CHECK", 0);
  5. define("HEAD_FIELD_CHECK", 1);
  6. define("QUERY_STRING_CHECK", 2);
  7. // ----------------------------------------------------------
  8. function CanonicalizedResource($bucket, $key)
  9. {
  10. return "/" . $bucket . "/" . $key;
  11. }
  12. function CanonicalizedUCloudHeaders($headers)
  13. {
  14. $keys = array();
  15. foreach($headers as $header) {
  16. $header = trim($header);
  17. $arr = explode(':', $header);
  18. if (count($arr) < 2) continue;
  19. list($k, $v) = $arr;
  20. $k = strtolower($k);
  21. if (strncasecmp($k, "x-ucloud") === 0) {
  22. $keys[] = $k;
  23. }
  24. }
  25. $c = '';
  26. sort($keys, SORT_STRING);
  27. foreach($keys as $k) {
  28. $c .= $k . ":" . trim($headers[$v], " ") . "\n";
  29. }
  30. return $c;
  31. }
  32. class UCloud_Auth {
  33. public $PublicKey;
  34. public $PrivateKey;
  35. public function __construct($publicKey, $privateKey)
  36. {
  37. $this->PublicKey = $publicKey;
  38. $this->PrivateKey = $privateKey;
  39. }
  40. public function Sign($data)
  41. {
  42. $sign = base64_encode(hash_hmac('sha1', $data, $this->PrivateKey, true));
  43. return "UCloud " . $this->PublicKey . ":" . $sign;
  44. }
  45. //@results: $token
  46. public function SignRequest($req, $mimetype = null, $type = HEAD_FIELD_CHECK)
  47. {
  48. $url = $req->URL;
  49. $url = parse_url($url['path']);
  50. $data = '';
  51. $data .= strtoupper($req->METHOD) . "\n";
  52. $data .= UCloud_Header_Get($req->Header, 'Content-MD5') . "\n";
  53. if ($mimetype)
  54. $data .= $mimetype . "\n";
  55. else
  56. $data .= UCloud_Header_Get($req->Header, 'Content-Type') . "\n";
  57. if ($type === HEAD_FIELD_CHECK)
  58. $data .= UCloud_Header_Get($req->Header, 'Date') . "\n";
  59. else
  60. $data .= UCloud_Header_Get($req->Header, 'Expires') . "\n";
  61. $data .= CanonicalizedUCloudHeaders($req->Header);
  62. $data .= CanonicalizedResource($req->Bucket, $req->Key);
  63. return $this->Sign($data);
  64. }
  65. }
  66. function UCloud_MakeAuth($auth)
  67. {
  68. if (isset($auth)) {
  69. return $auth;
  70. }
  71. global $UCLOUD_PUBLIC_KEY;
  72. global $UCLOUD_PRIVATE_KEY;
  73. return new UCloud_Auth($UCLOUD_PUBLIC_KEY, $UCLOUD_PRIVATE_KEY);
  74. }
  75. //@results: token
  76. function UCloud_SignRequest($auth, $req, $type = HEAD_FIELD_CHECK)
  77. {
  78. return UCloud_MakeAuth($auth)->SignRequest($req, $type);
  79. }
  80. // ----------------------------------------------------------