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 if (obj instanceof byte[]) 31 { 32 try 33 { 34 return (DERVisibleString)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: " + obj.getClass().getName()); 43 } 44 45 /** 46 * return a Visible String from a tagged object. 47 * 48 * @param obj the tagged object holding the object we want 49 * @param explicit true if the object is meant to be explicitly 50 * tagged false otherwise. 51 * @exception IllegalArgumentException if the tagged object cannot 52 * be converted. 53 */ 54 public static DERVisibleString getInstance( 55 ASN1TaggedObject obj, 56 boolean explicit) 57 { 58 ASN1Primitive o = obj.getObject(); 59 60 if (explicit || o instanceof DERVisibleString) 61 { 62 return getInstance(o); 63 } 64 else 65 { 66 return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets()); 67 } 68 } 69 70 /** 71 * basic constructor - byte encoded string. 72 */ 73 DERVisibleString( 74 byte[] string) 75 { 76 this.string = string; 77 } 78 79 /** 80 * basic constructor 81 */ 82 public DERVisibleString( 83 String string) 84 { 85 this.string = Strings.toByteArray(string); 86 } 87 88 public String getString() 89 { 90 return Strings.fromByteArray(string); 91 } 92 93 public String toString() 94 { 95 return getString(); 96 } 97 98 public byte[] getOctets() 99 { 100 return Arrays.clone(string); 101 } 102 103 boolean isConstructed() 104 { 105 return false; 106 } 107 108 int encodedLength() 109 { 110 return 1 + StreamUtil.calculateBodyLength(string.length) + string.length; 111 } 112 113 void encode( 114 ASN1OutputStream out) 115 throws IOException 116 { 117 out.writeEncoded(BERTags.VISIBLE_STRING, this.string); 118 } 119 120 boolean asn1Equals( 121 ASN1Primitive o) 122 { 123 if (!(o instanceof DERVisibleString)) 124 { 125 return false; 126 } 127 128 return Arrays.areEqual(string, ((DERVisibleString)o).string); 129 } 130 131 public int hashCode() 132 { 133 return Arrays.hashCode(string); 134 } 135} 136