1package org.bouncycastle.asn1; 2 3import java.io.ByteArrayInputStream; 4import java.io.IOException; 5import java.io.InputStream; 6 7import org.bouncycastle.util.Arrays; 8import org.bouncycastle.util.encoders.Hex; 9 10public abstract class ASN1OctetString 11 extends ASN1Object 12 implements ASN1OctetStringParser 13{ 14 byte[] string; 15 16 /** 17 * return an Octet String from a tagged object. 18 * 19 * @param obj the tagged object holding the object we want. 20 * @param explicit true if the object is meant to be explicitly 21 * tagged false otherwise. 22 * @exception IllegalArgumentException if the tagged object cannot 23 * be converted. 24 */ 25 public static ASN1OctetString getInstance( 26 ASN1TaggedObject obj, 27 boolean explicit) 28 { 29 DERObject o = obj.getObject(); 30 31 if (explicit || o instanceof ASN1OctetString) 32 { 33 return getInstance(o); 34 } 35 else 36 { 37 return BERConstructedOctetString.fromSequence(ASN1Sequence.getInstance(o)); 38 } 39 } 40 41 /** 42 * return an Octet String from the given object. 43 * 44 * @param obj the object we want converted. 45 * @exception IllegalArgumentException if the object cannot be converted. 46 */ 47 public static ASN1OctetString getInstance( 48 Object obj) 49 { 50 if (obj == null || obj instanceof ASN1OctetString) 51 { 52 return (ASN1OctetString)obj; 53 } 54 55 // TODO: this needs to be deleted in V2 56 if (obj instanceof ASN1TaggedObject) 57 { 58 return getInstance(((ASN1TaggedObject)obj).getObject()); 59 } 60 61 throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); 62 } 63 64 /** 65 * @param string the octets making up the octet string. 66 */ 67 public ASN1OctetString( 68 byte[] string) 69 { 70 if (string == null) 71 { 72 throw new NullPointerException("string cannot be null"); 73 } 74 this.string = string; 75 } 76 77 public ASN1OctetString( 78 DEREncodable obj) 79 { 80 try 81 { 82 this.string = obj.getDERObject().getEncoded(ASN1Encodable.DER); 83 } 84 catch (IOException e) 85 { 86 throw new IllegalArgumentException("Error processing object : " + e.toString()); 87 } 88 } 89 90 public InputStream getOctetStream() 91 { 92 return new ByteArrayInputStream(string); 93 } 94 95 public ASN1OctetStringParser parser() 96 { 97 return this; 98 } 99 100 public byte[] getOctets() 101 { 102 return string; 103 } 104 105 public int hashCode() 106 { 107 return Arrays.hashCode(this.getOctets()); 108 } 109 110 boolean asn1Equals( 111 DERObject o) 112 { 113 if (!(o instanceof ASN1OctetString)) 114 { 115 return false; 116 } 117 118 ASN1OctetString other = (ASN1OctetString)o; 119 120 return Arrays.areEqual(string, other.string); 121 } 122 123 public DERObject getLoadedObject() 124 { 125 return this.getDERObject(); 126 } 127 128 abstract void encode(DEROutputStream out) 129 throws IOException; 130 131 public String toString() 132 { 133 return "#"+new String(Hex.encode(string)); 134 } 135} 136