Signature.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace Qcloud\Cos;
  3. use Psr\Http\Message\RequestInterface;
  4. class Signature {
  5. private $accessKey; // string: access key.
  6. private $secretKey; // string: secret key.
  7. public function __construct($accessKey, $secretKey, $token=null) {
  8. $this->accessKey = $accessKey;
  9. $this->secretKey = $secretKey;
  10. $this->token = $token;
  11. date_default_timezone_set("PRC");
  12. }
  13. public function __destruct() {
  14. }
  15. public function signRequest(RequestInterface $request) {
  16. $authorization = $this->createAuthorization($request);
  17. return $request->withHeader('Authorization', $authorization);
  18. }
  19. public function createAuthorization(RequestInterface $request, $expires = "+30 minutes") {
  20. if (is_null($expires)) {
  21. $expires = "+30 minutes";
  22. }
  23. $signTime = (string)(time() - 60) . ';' . (string)(strtotime($expires));
  24. $httpString = strtolower($request->getMethod()) . "\n" . urldecode($request->getUri()->getPath()) .
  25. "\n\nhost=" . $request->getHeader("Host")[0]. "\n";
  26. $sha1edHttpString = sha1($httpString);
  27. $stringToSign = "sha1\n$signTime\n$sha1edHttpString\n";
  28. $signKey = hash_hmac('sha1', $signTime, $this->secretKey);
  29. $signature = hash_hmac('sha1', $stringToSign, $signKey);
  30. $authorization = 'q-sign-algorithm=sha1&q-ak='. $this->accessKey .
  31. "&q-sign-time=$signTime&q-key-time=$signTime&q-header-list=host&q-url-param-list=&" .
  32. "q-signature=$signature";
  33. return $authorization;
  34. }
  35. public function createPresignedUrl(RequestInterface $request, $expires = "+30 minutes") {
  36. $authorization = $this->createAuthorization($request, $expires);
  37. $uri = $request->getUri();
  38. $query = "sign=".urlencode($authorization);
  39. if ($this->token != null) {
  40. $query = $query."&x-cos-security-token=".$this->token;
  41. }
  42. $uri = $uri->withQuery($query);
  43. return $uri;
  44. }
  45. }