initial checkin
[org.ibex.nanogoat.git] / src / org / bouncycastle / asn1 / DERUniversalString.java
1 package org.bouncycastle.asn1;
2
3 import java.io.*;
4
5 /**
6  * DER UniversalString object.
7  */
8 public class DERUniversalString
9     extends DERObject
10     implements DERString
11 {
12     byte[]  string;
13     char[]  table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
14
15     /**
16      * return a Universal String from the passed in object.
17      *
18      * @exception IllegalArgumentException if the object cannot be converted.
19      */
20     public static DERUniversalString getInstance(
21         Object  obj)
22     {
23         if (obj == null || obj instanceof DERUniversalString)
24         {
25             return (DERUniversalString)obj;
26         }
27
28         if (obj instanceof ASN1OctetString)
29         {
30             return new DERUniversalString(((ASN1OctetString)obj).getOctets());
31         }
32
33         throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
34     }
35
36     /**
37      * return a Universal String from a tagged object.
38      *
39      * @param obj the tagged object holding the object we want
40      * @param explicit true if the object is meant to be explicitly
41      *              tagged false otherwise.
42      * @exception IllegalArgumentException if the tagged object cannot
43      *               be converted.
44      */
45     public static DERUniversalString getInstance(
46         ASN1TaggedObject obj,
47         boolean          explicit)
48     {
49         return getInstance(obj.getObject());
50     }
51
52     /**
53      * basic constructor - byte encoded string.
54      */
55     public DERUniversalString(
56         byte[]   string)
57     {
58         this.string = string;
59     }
60
61     /**
62      * UniversalStrings have characters which are 4 bytes long - for the
63      * moment we just return them in Hex...
64      */
65     public String getString()
66     {
67         StringBuffer    buf = new StringBuffer();
68
69         for (int i = 0; i != string.length; i++)
70         {
71             buf.append(table[(string[i] >>> 4) % 0xf]);
72             buf.append(table[string[i] & 0xf]);
73         }
74
75         return buf.toString();
76     }
77
78     public byte[] getOctets()
79     {
80         return string;
81     }
82
83     void encode(
84         DEROutputStream  out)
85         throws IOException
86     {
87         out.writeEncoded(UNIVERSAL_STRING, this.getOctets());
88     }
89     
90     public boolean equals(
91         Object  o)
92     {
93         if ((o == null) || !(o instanceof DERUniversalString))
94         {
95             return false;
96         }
97
98         return this.getString().equals(((DERUniversalString)o).getString());
99     }
100 }