OAuthSignatureMethod_HMAC.inc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * A generic signature method implementation that leverages hash_hmac() for
  4. * increased flexibility.
  5. */
  6. class OAuthSignatureMethod_HMAC extends OAuthSignatureMethod {
  7. private $algo = NULL;
  8. /**
  9. * Create a HMAC oauth signature method object using the (or one of the)
  10. * specified algorithm implementations.
  11. *
  12. * @param mixed $algo
  13. * Pass the name of a algorithm supported by hash_hmac() or an array of
  14. * names when you have several candidate algorithms that may be used. The
  15. * first algorithm int the array that is supported on the system will be used.
  16. * @throws Exception
  17. * A exception is thrown when none of the provided algorithms are supported
  18. * by the system.
  19. */
  20. public function __construct($algo) {
  21. $algos = hash_algos();
  22. // Create a single-element array from strings to simplify the logic of
  23. // support checking and failure handling.
  24. if (is_string($algo)) {
  25. $algo = array($algo);
  26. }
  27. // Find a supported algorithm among the candidates
  28. foreach ($algo as $a) {
  29. if (in_array(strtolower($a), $algos)) {
  30. $this->algo = strtolower($a);
  31. continue;
  32. }
  33. }
  34. // Throw a exception if no matching algorithm can be found
  35. if (empty($this->algo)) {
  36. throw new OAuthException(t('None of the suggested hash algorithms (@cand) were '
  37. . 'supported by the server. Try one of the following: !algos.', array(
  38. '@cand' => join($algo, ', '),
  39. '!algos' => join($algos, ', '),
  40. )));
  41. }
  42. }
  43. public function get_name() {
  44. return "HMAC-" . strtoupper($this->algo);
  45. }
  46. public function build_signature($request, $consumer, $token) {
  47. $base_string = $request->get_signature_base_string();
  48. $request->base_string = $base_string;
  49. $key_parts = array(
  50. $consumer->secret,
  51. ($token) ? $token->secret : ""
  52. );
  53. $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
  54. $key = implode('&', $key_parts);
  55. return base64_encode(hash_hmac($this->algo, $base_string, $key, TRUE));
  56. }
  57. }