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