Certificate.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Security;
  9. use OCP\ICertificate;
  10. class Certificate implements ICertificate {
  11. protected string $name;
  12. protected ?string $commonName;
  13. protected ?string $organization;
  14. protected \DateTime $issueDate;
  15. protected \DateTime $expireDate;
  16. protected ?string $issuerName;
  17. protected ?string $issuerOrganization;
  18. /**
  19. * @param string $data base64 encoded certificate
  20. * @throws \Exception If the certificate could not get parsed
  21. */
  22. public function __construct(string $data, string $name) {
  23. $this->name = $name;
  24. $gmt = new \DateTimeZone('GMT');
  25. // If string starts with "file://" ignore the certificate
  26. $query = 'file://';
  27. if (strtolower(substr($data, 0, strlen($query))) === $query) {
  28. throw new \Exception('Certificate could not get parsed.');
  29. }
  30. $info = openssl_x509_parse($data);
  31. if (!is_array($info)) {
  32. throw new \Exception('Certificate could not get parsed.');
  33. }
  34. $this->commonName = $info['subject']['CN'] ?? null;
  35. $this->organization = $info['subject']['O'] ?? null;
  36. $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt);
  37. $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt);
  38. $this->issuerName = $info['issuer']['CN'] ?? null;
  39. $this->issuerOrganization = $info['issuer']['O'] ?? null;
  40. }
  41. public function getName(): string {
  42. return $this->name;
  43. }
  44. public function getCommonName(): ?string {
  45. return $this->commonName;
  46. }
  47. public function getOrganization(): ?string {
  48. return $this->organization;
  49. }
  50. public function getIssueDate(): \DateTime {
  51. return $this->issueDate;
  52. }
  53. public function getExpireDate(): \DateTime {
  54. return $this->expireDate;
  55. }
  56. public function isExpired(): bool {
  57. $now = new \DateTime();
  58. return $this->issueDate > $now or $now > $this->expireDate;
  59. }
  60. public function getIssuerName(): ?string {
  61. return $this->issuerName;
  62. }
  63. public function getIssuerOrganization(): ?string {
  64. return $this->issuerOrganization;
  65. }
  66. }