Moodle authentication plugin for Macaroons

Utils.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Macaroons;
  3. class Utils
  4. {
  5. public static function hexlify($value)
  6. {
  7. return join('', array_map(function($byte){
  8. return sprintf("%02X", $byte);
  9. }, unpack('C*', $value)));
  10. }
  11. public static function unhexlify($value)
  12. {
  13. return pack('H*', $value);
  14. }
  15. public static function hmac($key, $data, $digest = 'sha256')
  16. {
  17. return hash_hmac($digest, $data, $key, true);
  18. }
  19. public static function generateDerivedKey($key)
  20. {
  21. return self::hmac('macaroons-key-generator', $key);
  22. }
  23. public static function truncateOrPad($str, $size = 32)
  24. {
  25. if (strlen($str) > $size)
  26. return substr($str, 0, $size);
  27. else if (strlen($str) < $size)
  28. return str_pad($str, $size, "\0", STR_PAD_RIGHT);
  29. return $str;
  30. }
  31. public static function startsWith($str, $prefix)
  32. {
  33. if (!(is_string($str) && is_string($prefix)))
  34. throw new \InvalidArgumentException('Both arguments must be strings');
  35. return substr($str, 0, strlen($prefix)) === $prefix;
  36. }
  37. public static function base64_strict_encode($data)
  38. {
  39. $data = str_replace("\r\n", '', base64_encode($data));
  40. $data = str_replace("\r", '', $data);
  41. return str_replace("\n", '', $data);
  42. }
  43. public static function base64_url_safe_encode($data)
  44. {
  45. $data = str_replace('+', '-', self::base64_strict_encode($data));
  46. return str_replace('/', '_', $data);
  47. }
  48. public static function base64_url_safe_decode($data)
  49. {
  50. $data = str_replace('-', '+', $data);
  51. $data = str_replace('_', '/', $data);
  52. return base64_decode($data);
  53. }
  54. public static function base64_url_encode($data)
  55. {
  56. return str_replace('=', '', self::base64_url_safe_encode($data));
  57. }
  58. public static function base64_url_decode($data)
  59. {
  60. return self::base64_url_safe_decode(str_pad($data, (4 - (strlen($data) % 4)) % 4, '=', STR_PAD_RIGHT));
  61. }
  62. public static function signFirstPartyCaveat($signature, $predicate)
  63. {
  64. return self::hmac($signature, $predicate);
  65. }
  66. public static function signThirdPartyCaveat($signature, $verificationId, $caveatId)
  67. {
  68. $verification_id_hmac = self::hmac($signature, $verificationId);
  69. $caveat_id_hmac = self::hmac($signature, $caveatId);
  70. $combined = $verification_id_hmac . $caveat_id_hmac;
  71. return self::hmac($signature, $combined);
  72. }
  73. }