1package org.bouncycastle.asn1;
2
3import java.io.IOException;
4import java.math.BigInteger;
5
6import org.bouncycastle.util.Arrays;
7
8public class DERInteger
9    extends ASN1Object
10{
11    byte[]      bytes;
12
13    /**
14     * return an integer from the passed in object
15     *
16     * @exception IllegalArgumentException if the object cannot be converted.
17     */
18    public static DERInteger getInstance(
19        Object  obj)
20    {
21        if (obj == null || obj instanceof DERInteger)
22        {
23            return (DERInteger)obj;
24        }
25
26        throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
27    }
28
29    /**
30     * return an Integer from a tagged object.
31     *
32     * @param obj the tagged object holding the object we want
33     * @param explicit true if the object is meant to be explicitly
34     *              tagged false otherwise.
35     * @exception IllegalArgumentException if the tagged object cannot
36     *               be converted.
37     */
38    public static DERInteger getInstance(
39        ASN1TaggedObject obj,
40        boolean          explicit)
41    {
42        DERObject o = obj.getObject();
43
44        if (explicit || o instanceof DERInteger)
45        {
46            return getInstance(o);
47        }
48        else
49        {
50            return new ASN1Integer(ASN1OctetString.getInstance(obj.getObject()).getOctets());
51        }
52    }
53
54    public DERInteger(
55        int         value)
56    {
57        bytes = BigInteger.valueOf(value).toByteArray();
58    }
59
60    public DERInteger(
61        BigInteger   value)
62    {
63        bytes = value.toByteArray();
64    }
65
66    public DERInteger(
67        byte[]   bytes)
68    {
69        this.bytes = bytes;
70    }
71
72    public BigInteger getValue()
73    {
74        return new BigInteger(bytes);
75    }
76
77    /**
78     * in some cases positive values get crammed into a space,
79     * that's not quite big enough...
80     */
81    public BigInteger getPositiveValue()
82    {
83        return new BigInteger(1, bytes);
84    }
85
86    void encode(
87        DEROutputStream out)
88        throws IOException
89    {
90        out.writeEncoded(INTEGER, bytes);
91    }
92
93    public int hashCode()
94    {
95         int     value = 0;
96
97         for (int i = 0; i != bytes.length; i++)
98         {
99             value ^= (bytes[i] & 0xff) << (i % 4);
100         }
101
102         return value;
103    }
104
105    boolean asn1Equals(
106        DERObject  o)
107    {
108        if (!(o instanceof DERInteger))
109        {
110            return false;
111        }
112
113        DERInteger other = (DERInteger)o;
114
115        return Arrays.areEqual(bytes, other.bytes);
116    }
117
118    public String toString()
119    {
120      return getValue().toString();
121    }
122}
123