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