RequestValidator.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Twilio\Security;
  3. class RequestValidator {
  4. protected $authToken;
  5. function __construct($authToken) {
  6. $this->authToken = $authToken;
  7. }
  8. public function computeSignature($url, $data = array()) {
  9. // sort the array by keys
  10. ksort($data);
  11. // append them to the data string in order
  12. // with no delimiters
  13. foreach ($data as $key => $value)
  14. $url .= "$key$value";
  15. // This function calculates the HMAC hash of the data with the key
  16. // passed in
  17. // Note: hash_hmac requires PHP 5 >= 5.1.2 or PECL hash:1.1-1.5
  18. // Or http://pear.php.net/package/Crypt_HMAC/
  19. return base64_encode(hash_hmac("sha1", $url, $this->authToken, true));
  20. }
  21. public function validate($expectedSignature, $url, $data = array()) {
  22. return self::compare(
  23. $this->computeSignature($url, $data),
  24. $expectedSignature
  25. );
  26. }
  27. /**
  28. * Time insensitive compare, function's runtime is governed by the length
  29. * of the first argument, not the difference between the arguments.
  30. * @param $a string First part of the comparison pair
  31. * @param $b string Second part of the comparison pair
  32. * @return bool True if $a == $b, false otherwise.
  33. */
  34. public
  35. static function compare($a, $b) {
  36. $result = true;
  37. if (strlen($a) != strlen($b)) {
  38. return false;
  39. }
  40. if (!$a && !$b) {
  41. return true;
  42. }
  43. $limit = strlen($a);
  44. for ($i = 0; $i < $limit; ++$i) {
  45. if ($a[$i] != $b[$i]) {
  46. $result = false;
  47. }
  48. }
  49. return $result;
  50. }
  51. }