DERUTF8String.java revision e6bf3e8dfa2804891a82075cb469b736321b4827
1package org.bouncycastle.asn1;
2
3import java.io.IOException;
4
5import org.bouncycastle.util.Arrays;
6import org.bouncycastle.util.Strings;
7
8/**
9 * DER UTF8String object.
10 */
11public class DERUTF8String
12    extends ASN1Primitive
13    implements ASN1String
14{
15    private byte[]  string;
16
17    /**
18     * return an UTF8 string from the passed in object.
19     *
20     * @exception IllegalArgumentException
21     *                if the object cannot be converted.
22     */
23    public static DERUTF8String getInstance(Object obj)
24    {
25        if (obj == null || obj instanceof DERUTF8String)
26        {
27            return (DERUTF8String)obj;
28        }
29
30        throw new IllegalArgumentException("illegal object in getInstance: "
31                + obj.getClass().getName());
32    }
33
34    /**
35     * return an UTF8 String from a tagged object.
36     *
37     * @param obj
38     *            the tagged object holding the object we want
39     * @param explicit
40     *            true if the object is meant to be explicitly tagged false
41     *            otherwise.
42     * @exception IllegalArgumentException
43     *                if the tagged object cannot be converted.
44     */
45    public static DERUTF8String getInstance(
46        ASN1TaggedObject obj,
47        boolean explicit)
48    {
49        ASN1Primitive o = obj.getObject();
50
51        if (explicit || o instanceof DERUTF8String)
52        {
53            return getInstance(o);
54        }
55        else
56        {
57            return new DERUTF8String(ASN1OctetString.getInstance(o).getOctets());
58        }
59    }
60
61    /**
62     * basic constructor - byte encoded string.
63     */
64    DERUTF8String(byte[] string)
65    {
66        this.string = string;
67    }
68
69    /**
70     * basic constructor
71     */
72    public DERUTF8String(String string)
73    {
74        this.string = Strings.toUTF8ByteArray(string);
75    }
76
77    public String getString()
78    {
79        return Strings.fromUTF8ByteArray(string);
80    }
81
82    public String toString()
83    {
84        return getString();
85    }
86
87    public int hashCode()
88    {
89        return Arrays.hashCode(string);
90    }
91
92    boolean asn1Equals(ASN1Primitive o)
93    {
94        if (!(o instanceof DERUTF8String))
95        {
96            return false;
97        }
98
99        DERUTF8String s = (DERUTF8String)o;
100
101        return Arrays.areEqual(string, s.string);
102    }
103
104    boolean isConstructed()
105    {
106        return false;
107    }
108
109    int encodedLength()
110        throws IOException
111    {
112        return 1 + StreamUtil.calculateBodyLength(string.length) + string.length;
113    }
114
115    void encode(ASN1OutputStream out)
116        throws IOException
117    {
118        out.writeEncoded(BERTags.UTF8_STRING, string);
119    }
120}
121