IPAddress.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /*
  3. * This file is part of the PHPASN1 library.
  4. *
  5. * Copyright © Friedrich Große <friedrich.grosse@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace FG\X509\SAN;
  11. use FG\ASN1\ASNObject;
  12. use FG\ASN1\Parsable;
  13. use FG\ASN1\Exception\ParserException;
  14. class IPAddress extends ASNObject implements Parsable
  15. {
  16. const IDENTIFIER = 0x87; // not sure yet why this is the identifier used in SAN extensions
  17. /** @var string */
  18. private $value;
  19. public function __construct($ipAddressString)
  20. {
  21. $this->value = $ipAddressString;
  22. }
  23. public function getType()
  24. {
  25. return self::IDENTIFIER;
  26. }
  27. public function getContent()
  28. {
  29. return $this->value;
  30. }
  31. protected function calculateContentLength()
  32. {
  33. return 4;
  34. }
  35. protected function getEncodedValue()
  36. {
  37. $ipParts = explode('.', $this->value);
  38. $binary = chr($ipParts[0]);
  39. $binary .= chr($ipParts[1]);
  40. $binary .= chr($ipParts[2]);
  41. $binary .= chr($ipParts[3]);
  42. return $binary;
  43. }
  44. public static function fromBinary(&$binaryData, &$offsetIndex = 0)
  45. {
  46. self::parseIdentifier($binaryData[$offsetIndex], self::IDENTIFIER, $offsetIndex++);
  47. $contentLength = self::parseContentLength($binaryData, $offsetIndex);
  48. if ($contentLength != 4) {
  49. throw new ParserException("A FG\\X509\SAN\IPAddress should have a content length of 4. Extracted length was {$contentLength}", $offsetIndex);
  50. }
  51. $ipAddressString = ord($binaryData[$offsetIndex++]).'.';
  52. $ipAddressString .= ord($binaryData[$offsetIndex++]).'.';
  53. $ipAddressString .= ord($binaryData[$offsetIndex++]).'.';
  54. $ipAddressString .= ord($binaryData[$offsetIndex++]);
  55. $parsedObject = new self($ipAddressString);
  56. $parsedObject->getObjectLength();
  57. return $parsedObject;
  58. }
  59. }