1 package org.bouncycastle.asn1; 2 3 import java.io.IOException; 4 5 import org.bouncycastle.util.Arrays; 6 import org.bouncycastle.util.Strings; 7 8 /** 9 * DER UTF8String object. 10 */ 11 public 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 if (obj instanceof byte[]) 31 { 32 try 33 { 34 return (DERUTF8String)fromByteArray((byte[])obj); 35 } 36 catch (Exception e) 37 { 38 throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); 39 } 40 } 41 42 throw new IllegalArgumentException("illegal object in getInstance: " 43 + obj.getClass().getName()); 44 } 45 46 /** 47 * return an UTF8 String from a tagged object. 48 * 49 * @param obj 50 * the tagged object holding the object we want 51 * @param explicit 52 * true if the object is meant to be explicitly tagged false 53 * otherwise. 54 * @exception IllegalArgumentException 55 * if the tagged object cannot be converted. 56 */ 57 public static DERUTF8String getInstance( 58 ASN1TaggedObject obj, 59 boolean explicit) 60 { 61 ASN1Primitive o = obj.getObject(); 62 63 if (explicit || o instanceof DERUTF8String) 64 { 65 return getInstance(o); 66 } 67 else 68 { 69 return new DERUTF8String(ASN1OctetString.getInstance(o).getOctets()); 70 } 71 } 72 73 /** 74 * basic constructor - byte encoded string. 75 */ 76 DERUTF8String(byte[] string) 77 { 78 this.string = string; 79 } 80 81 /** 82 * basic constructor 83 */ 84 public DERUTF8String(String string) 85 { 86 this.string = Strings.toUTF8ByteArray(string); 87 } 88 89 public String getString() 90 { 91 return Strings.fromUTF8ByteArray(string); 92 } 93 94 public String toString() 95 { 96 return getString(); 97 } 98 99 public int hashCode() 100 { 101 return Arrays.hashCode(string); 102 } 103 104 boolean asn1Equals(ASN1Primitive o) 105 { 106 if (!(o instanceof DERUTF8String)) 107 { 108 return false; 109 } 110 111 DERUTF8String s = (DERUTF8String)o; 112 113 return Arrays.areEqual(string, s.string); 114 } 115 116 boolean isConstructed() 117 { 118 return false; 119 } 120 121 int encodedLength() 122 throws IOException 123 { 124 return 1 + StreamUtil.calculateBodyLength(string.length) + string.length; 125 } 126 127 void encode(ASN1OutputStream out) 128 throws IOException 129 { 130 out.writeEncoded(BERTags.UTF8_STRING, string); 131 } 132 } 133