Auth.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace UCloud;
  3. class Auth {
  4. public $PublicKey;
  5. public $PrivateKey;
  6. public $ProxySuffix;
  7. public function __construct($publicKey, $privateKey, $proxySuffix) {
  8. $this->PublicKey = $publicKey;
  9. $this->PrivateKey = $privateKey;
  10. $this->ProxySuffix = $proxySuffix;
  11. }
  12. private function CanonicalizedResource($bucket, $key) {
  13. return "/" . $bucket . "/" . $key;
  14. }
  15. private function CanonicalizedUCloudHeaders($headers) {
  16. $keys = array();
  17. foreach($headers as $header) {
  18. $header = trim($header);
  19. $arr = explode(':', $header);
  20. if (count($arr) < 2) {
  21. continue;
  22. }
  23. list($k, $v) = $arr;
  24. $k = strtolower($k);
  25. if (strncasecmp($k, "x-ucloud") === 0) {
  26. $keys[] = $k;
  27. }
  28. }
  29. $c = '';
  30. sort($keys, SORT_STRING);
  31. foreach($keys as $k) {
  32. $c .= $k . ":" . trim($headers[$v], " ") . "\n";
  33. }
  34. return $c;
  35. }
  36. public function Sign($data) {
  37. $sign = base64_encode(hash_hmac('sha1', $data, $this->PrivateKey, true));
  38. return "UCloud " . $this->PublicKey . ":" . $sign;
  39. }
  40. //@results: $token
  41. public function SignRequest($req, $mimetype = null, $type = Config::HEAD_FIELD_CHECK) {
  42. $url = $req->URL;
  43. $url = parse_url($url['path']);
  44. $data = '';
  45. $data .= strtoupper($req->METHOD) . "\n";
  46. $data .= Header_Get($req->Header, 'Content-MD5') . "\n";
  47. if ($mimetype)
  48. $data .= $mimetype . "\n";
  49. else
  50. $data .= Header_Get($req->Header, 'Content-Type') . "\n";
  51. if ($type === Config::HEAD_FIELD_CHECK)
  52. $data .= Header_Get($req->Header, 'Date') . "\n";
  53. else
  54. $data .= Header_Get($req->Header, 'Expires') . "\n";
  55. $data .= $this->CanonicalizedUCloudHeaders($req->Header);
  56. $data .= $this->CanonicalizedResource($req->Bucket, $req->Key);
  57. return $this->Sign($data);
  58. }
  59. }