001package org.apache.commons.ssl.org.bouncycastle.asn1; 002 003import java.io.IOException; 004 005import org.bouncycastle.util.Arrays; 006import org.bouncycastle.util.Strings; 007 008/** 009 * DER UTF8String object. 010 */ 011public class DERUTF8String 012 extends ASN1Primitive 013 implements ASN1String 014{ 015 private byte[] string; 016 017 /** 018 * Return an UTF8 string from the passed in object. 019 * 020 * @param obj a DERUTF8String or an object that can be converted into one. 021 * @exception IllegalArgumentException 022 * if the object cannot be converted. 023 * @return a DERUTF8String instance, or null 024 */ 025 public static DERUTF8String getInstance(Object obj) 026 { 027 if (obj == null || obj instanceof DERUTF8String) 028 { 029 return (DERUTF8String)obj; 030 } 031 032 if (obj instanceof byte[]) 033 { 034 try 035 { 036 return (DERUTF8String)fromByteArray((byte[])obj); 037 } 038 catch (Exception e) 039 { 040 throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); 041 } 042 } 043 044 throw new IllegalArgumentException("illegal object in getInstance: " 045 + obj.getClass().getName()); 046 } 047 048 /** 049 * Return an UTF8 String from a tagged object. 050 * 051 * @param obj 052 * the tagged object holding the object we want 053 * @param explicit 054 * true if the object is meant to be explicitly tagged false 055 * otherwise. 056 * @exception IllegalArgumentException 057 * if the tagged object cannot be converted. 058 * @return a DERUTF8String instance, or null 059 */ 060 public static DERUTF8String getInstance( 061 ASN1TaggedObject obj, 062 boolean explicit) 063 { 064 ASN1Primitive o = obj.getObject(); 065 066 if (explicit || o instanceof DERUTF8String) 067 { 068 return getInstance(o); 069 } 070 else 071 { 072 return new DERUTF8String(ASN1OctetString.getInstance(o).getOctets()); 073 } 074 } 075 076 /** 077 * Basic constructor - byte encoded string. 078 */ 079 DERUTF8String(byte[] string) 080 { 081 this.string = string; 082 } 083 084 /** 085 * Basic constructor 086 */ 087 public DERUTF8String(String string) 088 { 089 this.string = Strings.toUTF8ByteArray(string); 090 } 091 092 public String getString() 093 { 094 return Strings.fromUTF8ByteArray(string); 095 } 096 097 public String toString() 098 { 099 return getString(); 100 } 101 102 public int hashCode() 103 { 104 return Arrays.hashCode(string); 105 } 106 107 boolean asn1Equals(ASN1Primitive o) 108 { 109 if (!(o instanceof DERUTF8String)) 110 { 111 return false; 112 } 113 114 DERUTF8String s = (DERUTF8String)o; 115 116 return Arrays.areEqual(string, s.string); 117 } 118 119 boolean isConstructed() 120 { 121 return false; 122 } 123 124 int encodedLength() 125 throws IOException 126 { 127 return 1 + StreamUtil.calculateBodyLength(string.length) + string.length; 128 } 129 130 void encode(ASN1OutputStream out) 131 throws IOException 132 { 133 out.writeEncoded(BERTags.UTF8_STRING, string); 134 } 135}