1<?php
2/*
3 * Copyright 2008-2010 GuardTime AS
4 *
5 * This file is part of the GuardTime PHP SDK.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20/**
21 * @package asn1
22 */
23
24/**
25 * ASN.1 Integer implementation.
26 *
27 * @package asn1
28 */
29class ASN1Integer extends ASN1Object {
30
31    protected $value;
32
33    /**
34     * Constructs a new ASN1Integer.
35     *
36     * @throws GTException
37     * @param  int|GTBigInteger $value integer or GTBigInteger instance
38     * @return void
39     */
40    public function __construct($value = null) {
41
42        if (!is_null($value)) {
43
44            if (is_integer($value)) {
45                $this->value = new GTBigInteger($value);
46
47            } else if ($value instanceof GTBigInteger) {
48                $this->value = $value;
49
50            } else {
51                throw new GTException("value must be an int or GTBigInteger");
52            }
53        }
54    }
55
56    /**
57     * Gets the value of this ASN1Integer.
58     *
59     * @return string value as string
60     */
61    public function getValue() {
62        return $this->value->getValue();
63    }
64
65    /**
66     * Encodes the contents of this ASN1Integer as DER.
67     *
68     * @return array DER encoding of this ASN1Integer
69     */
70    public function encodeDER() {
71
72        $bytes = $this->value->toBytes();
73
74        if ($this->value->comp(new GTBigInteger(0)) == -1) {
75
76            while (count($bytes) > 0) {
77
78                if ($bytes[0] == 0x0) {
79                    array_shift($bytes);
80
81                } else {
82                    break;
83
84                }
85            }
86
87            if ($bytes[0] >> 7 == 1) {
88                array_unshift($bytes, 0xFF);
89
90            } else {
91                $bytes[0] = ($bytes[0] | 0x80) & 0xFF;
92
93            }
94        }
95
96        $this->prepend($bytes, ASN1DER::encodeLength(count($bytes)));
97        $this->prepend($bytes, ASN1DER::encodeType(ASN1_TAG_INTEGER));
98
99        return $bytes;
100    }
101
102    /**
103     * Decodes an ASN1 Integer from the given byte stream.
104     *
105     * @param  array $bytes V bytes from the encoding of ASN1Integer TLV.
106     * @return void
107     */
108    public function decodeDER($bytes) {
109
110        $this->value = new GTBigInteger($bytes);
111
112    }
113
114}
115
116?>
117