1package org.bouncycastle.asn1; 2 3import java.io.ByteArrayOutputStream; 4import java.io.IOException; 5 6public abstract class ASN1Object 7 implements ASN1Encodable 8{ 9 /** 10 * Return the default BER or DER encoding for this object. 11 * 12 * @return BER/DER byte encoded object. 13 * @throws java.io.IOException on encoding error. 14 */ 15 public byte[] getEncoded() 16 throws IOException 17 { 18 ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 19 ASN1OutputStream aOut = new ASN1OutputStream(bOut); 20 21 aOut.writeObject(this); 22 23 return bOut.toByteArray(); 24 } 25 26 /** 27 * Return either the default for "BER" or a DER encoding if "DER" is specified. 28 * 29 * @param encoding name of encoding to use. 30 * @return byte encoded object. 31 * @throws IOException on encoding error. 32 */ 33 public byte[] getEncoded( 34 String encoding) 35 throws IOException 36 { 37 if (encoding.equals(ASN1Encoding.DER)) 38 { 39 ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 40 DEROutputStream dOut = new DEROutputStream(bOut); 41 42 dOut.writeObject(this); 43 44 return bOut.toByteArray(); 45 } 46 else if (encoding.equals(ASN1Encoding.DL)) 47 { 48 ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 49 DLOutputStream dOut = new DLOutputStream(bOut); 50 51 dOut.writeObject(this); 52 53 return bOut.toByteArray(); 54 } 55 56 return this.getEncoded(); 57 } 58 59 public int hashCode() 60 { 61 return this.toASN1Primitive().hashCode(); 62 } 63 64 public boolean equals( 65 Object o) 66 { 67 if (this == o) 68 { 69 return true; 70 } 71 72 if (!(o instanceof ASN1Encodable)) 73 { 74 return false; 75 } 76 77 ASN1Encodable other = (ASN1Encodable)o; 78 79 return this.toASN1Primitive().equals(other.toASN1Primitive()); 80 } 81 82 /** 83 * @deprecated use toASN1Primitive() 84 * @return the underlying primitive type. 85 */ 86 public ASN1Primitive toASN1Object() 87 { 88 return this.toASN1Primitive(); 89 } 90 91 protected static boolean hasEncodedTagValue(Object obj, int tagValue) 92 { 93 return (obj instanceof byte[]) && ((byte[])obj)[0] == tagValue; 94 } 95 96 public abstract ASN1Primitive toASN1Primitive(); 97} 98