001 package org.apache.commons.ssl.asn1;
002
003 import java.io.IOException;
004 import java.math.BigInteger;
005
006 public class DEREnumerated
007 extends ASN1Object {
008 byte[] bytes;
009
010 /**
011 * return an integer from the passed in object
012 *
013 * @throws IllegalArgumentException if the object cannot be converted.
014 */
015 public static DEREnumerated getInstance(
016 Object obj) {
017 if (obj == null || obj instanceof DEREnumerated) {
018 return (DEREnumerated) obj;
019 }
020
021 if (obj instanceof ASN1OctetString) {
022 return new DEREnumerated(((ASN1OctetString) obj).getOctets());
023 }
024
025 if (obj instanceof ASN1TaggedObject) {
026 return getInstance(((ASN1TaggedObject) obj).getObject());
027 }
028
029 throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
030 }
031
032 /**
033 * return an Enumerated from a tagged object.
034 *
035 * @param obj the tagged object holding the object we want
036 * @param explicit true if the object is meant to be explicitly
037 * tagged false otherwise.
038 * @throws IllegalArgumentException if the tagged object cannot
039 * be converted.
040 */
041 public static DEREnumerated getInstance(
042 ASN1TaggedObject obj,
043 boolean explicit) {
044 return getInstance(obj.getObject());
045 }
046
047 public DEREnumerated(
048 int value) {
049 bytes = BigInteger.valueOf(value).toByteArray();
050 }
051
052 public DEREnumerated(
053 BigInteger value) {
054 bytes = value.toByteArray();
055 }
056
057 public DEREnumerated(
058 byte[] bytes) {
059 this.bytes = bytes;
060 }
061
062 public BigInteger getValue() {
063 return new BigInteger(bytes);
064 }
065
066 void encode(
067 DEROutputStream out)
068 throws IOException {
069 out.writeEncoded(ENUMERATED, bytes);
070 }
071
072 boolean asn1Equals(
073 DERObject o) {
074 if (!(o instanceof DEREnumerated)) {
075 return false;
076 }
077
078 DEREnumerated other = (DEREnumerated) o;
079
080 if (bytes.length != other.bytes.length) {
081 return false;
082 }
083
084 for (int i = 0; i != bytes.length; i++) {
085 if (bytes[i] != other.bytes[i]) {
086 return false;
087 }
088 }
089
090 return true;
091 }
092
093 public int hashCode() {
094 return this.getValue().hashCode();
095 }
096 }