RsaAlgorithm.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Util\HttpSignatures;
  3. class RsaAlgorithm implements AlgorithmInterface
  4. {
  5. /** @var string */
  6. private $digestName;
  7. /**
  8. * @param string $digestName
  9. */
  10. public function __construct($digestName)
  11. {
  12. $this->digestName = $digestName;
  13. }
  14. /**
  15. * @return string
  16. */
  17. public function name()
  18. {
  19. return sprintf('rsa-%s', $this->digestName);
  20. }
  21. /**
  22. * @param string $key
  23. * @param string $data
  24. *
  25. * @return string
  26. *
  27. * @throws \HttpSignatures\AlgorithmException
  28. */
  29. public function sign($signingKey, $data)
  30. {
  31. $algo = $this->getRsaHashAlgo($this->digestName);
  32. if (!openssl_get_privatekey($signingKey)) {
  33. throw new AlgorithmException("OpenSSL doesn't understand the supplied key (not valid or not found)");
  34. }
  35. $signature = '';
  36. openssl_sign($data, $signature, $signingKey, $algo);
  37. return $signature;
  38. }
  39. public function verify($message, $signature, $verifyingKey)
  40. {
  41. $algo = $this->getRsaHashAlgo($this->digestName);
  42. return openssl_verify($message, base64_decode($signature), $verifyingKey, $algo);
  43. }
  44. private function getRsaHashAlgo($digestName)
  45. {
  46. switch ($digestName) {
  47. case 'sha256':
  48. return OPENSSL_ALGO_SHA256;
  49. case 'sha1':
  50. return OPENSSL_ALGO_SHA1;
  51. default:
  52. throw new HttpSignatures\AlgorithmException($digestName.' is not a supported hash format');
  53. }
  54. }
  55. }