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