1    package org.bouncycastle.asn1;
2    
3    import java.io.*;
4    import java.math.BigInteger;
5    
6    public class DEREnumerated
7        extends DERObject
8    {
9        byte[]      bytes;
10   
11       /**
12        * return an integer from the passed in object
13        *
14        * @exception IllegalArgumentException if the object cannot be converted.
15        */
16       public static DEREnumerated getInstance(
17           Object  obj)
18       {
19           if (obj == null || obj instanceof DEREnumerated)
20           {
21               return (DEREnumerated)obj;
22           }
23   
24           if (obj instanceof ASN1OctetString)
25           {
26               return new DEREnumerated(((ASN1OctetString)obj).getOctets());
27           }
28   
29           if (obj instanceof ASN1TaggedObject)
30           {
31               return getInstance(((ASN1TaggedObject)obj).getObject());
32           }
33   
34           throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
35       }
36   
37       /**
38        * return an Enumerated from a tagged object.
39        *
40        * @param obj the tagged object holding the object we want
41        * @param explicit true if the object is meant to be explicitly
42        *              tagged false otherwise.
43        * @exception IllegalArgumentException if the tagged object cannot
44        *               be converted.
45        */
46       public static DEREnumerated getInstance(
47           ASN1TaggedObject obj,
48           boolean          explicit)
49       {
50           return getInstance(obj.getObject());
51       }
52   
53       public DEREnumerated(
54           int         value)
55       {
56           bytes = BigInteger.valueOf(value).toByteArray();
57       }
58   
59       public DEREnumerated(
60           BigInteger   value)
61       {
62           bytes = value.toByteArray();
63       }
64   
65       public DEREnumerated(
66           byte[]   bytes)
67       {
68           this.bytes = bytes;
69       }
70   
71       public BigInteger getValue()
72       {
73           return new BigInteger(bytes);
74       }
75   
76       void encode(
77           DEROutputStream out)
78           throws IOException
79       {
80           out.writeEncoded(ENUMERATED, bytes);
81       }
82       
83       public boolean equals(
84           Object  o)
85       {
86           if (o == null || !(o instanceof DEREnumerated))
87           {
88               return false;
89           }
90   
91           DEREnumerated other = (DEREnumerated)o;
92   
93           if (bytes.length != other.bytes.length)
94           {
95               return false;
96           }
97   
98           for (int i = 0; i != bytes.length; i++)
99           {
100              if (bytes[i] != other.bytes[i])
101              {
102                  return false;
103              }
104          }
105  
106          return true;
107      }
108  }
109