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