ServiceAccountSignerTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /*
  3. * Copyright 2019 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\Auth;
  18. use phpseclib\Crypt\RSA;
  19. /**
  20. * Sign a string using a Service Account private key.
  21. */
  22. trait ServiceAccountSignerTrait
  23. {
  24. /**
  25. * Sign a string using the service account private key.
  26. *
  27. * @param string $stringToSign
  28. * @param bool $forceOpenssl Whether to use OpenSSL regardless of
  29. * whether phpseclib is installed. **Defaults to** `false`.
  30. * @return string
  31. */
  32. public function signBlob($stringToSign, $forceOpenssl = false)
  33. {
  34. $privateKey = $this->auth->getSigningKey();
  35. $signedString = '';
  36. if (class_exists('\\phpseclib\\Crypt\\RSA') && !$forceOpenssl) {
  37. $rsa = new RSA();
  38. $rsa->loadKey($privateKey);
  39. $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
  40. $rsa->setHash('sha256');
  41. $signedString = $rsa->sign($stringToSign);
  42. } elseif (extension_loaded('openssl')) {
  43. openssl_sign($stringToSign, $signedString, $privateKey, 'sha256WithRSAEncryption');
  44. } else {
  45. // @codeCoverageIgnoreStart
  46. throw new \RuntimeException('OpenSSL is not installed.');
  47. }
  48. // @codeCoverageIgnoreEnd
  49. return base64_encode($signedString);
  50. }
  51. }