OctetString.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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\ASN1\Universal;
  11. use Exception;
  12. use FG\ASN1\ASNObject;
  13. use FG\ASN1\Parsable;
  14. use FG\ASN1\Identifier;
  15. class OctetString extends ASNObject implements Parsable
  16. {
  17. protected $value;
  18. public function __construct($value)
  19. {
  20. if (is_string($value)) {
  21. // remove gaps between hex digits
  22. $value = preg_replace('/\s|0x/', '', $value);
  23. } elseif (is_numeric($value)) {
  24. $value = dechex($value);
  25. } elseif ($value === null) {
  26. return;
  27. } else {
  28. throw new Exception('OctetString: unrecognized input type!');
  29. }
  30. if (strlen($value) % 2 != 0) {
  31. // transform values like 1F2 to 01F2
  32. $value = '0'.$value;
  33. }
  34. $this->value = $value;
  35. }
  36. public function getType()
  37. {
  38. return Identifier::OCTETSTRING;
  39. }
  40. protected function calculateContentLength()
  41. {
  42. return strlen($this->value) / 2;
  43. }
  44. protected function getEncodedValue()
  45. {
  46. $value = $this->value;
  47. $result = '';
  48. //Actual content
  49. while (strlen($value) >= 2) {
  50. // get the hex value byte by byte from the string and and add it to binary result
  51. $result .= chr(hexdec(substr($value, 0, 2)));
  52. $value = substr($value, 2);
  53. }
  54. return $result;
  55. }
  56. public function getContent()
  57. {
  58. return strtoupper($this->value);
  59. }
  60. public function getBinaryContent()
  61. {
  62. return $this->getEncodedValue();
  63. }
  64. public static function fromBinary(&$binaryData, &$offsetIndex = 0)
  65. {
  66. self::parseIdentifier($binaryData[$offsetIndex], Identifier::OCTETSTRING, $offsetIndex++);
  67. $contentLength = self::parseContentLength($binaryData, $offsetIndex);
  68. $value = substr($binaryData, $offsetIndex, $contentLength);
  69. $offsetIndex += $contentLength;
  70. $parsedObject = new self(bin2hex($value));
  71. $parsedObject->setContentLength($contentLength);
  72. return $parsedObject;
  73. }
  74. }