1 package org.bouncycastle.asn1; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 6 /** 7 * Base class for objects which can be written directly to ASN.1 output streams. 8 */ 9 public abstract class ASN1Encodable 10 implements DEREncodable 11 { 12 public static final String DER = "DER"; 13 public static final String BER = "BER"; 14 15 /** 16 * Return the default BER or DER encoding for this object. 17 * 18 * @return BER/DER byte encoded object. 19 * @throws IOException on encoding error. 20 */ 21 public byte[] getEncoded() 22 throws IOException 23 { 24 ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 25 ASN1OutputStream aOut = new ASN1OutputStream(bOut); 26 27 aOut.writeObject(this); 28 29 return bOut.toByteArray(); 30 } 31 32 /** 33 * Return either the default for "BER" or a DER encoding if "DER" is specified. 34 * 35 * @param encoding name of encoding to use. 36 * @return byte encoded object. 37 * @throws IOException on encoding error. 38 */ 39 public byte[] getEncoded( 40 String encoding) 41 throws IOException 42 { 43 if (encoding.equals(DER)) 44 { 45 ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 46 DEROutputStream dOut = new DEROutputStream(bOut); 47 48 dOut.writeObject(this); 49 50 return bOut.toByteArray(); 51 } 52 53 return this.getEncoded(); 54 } 55 56 /** 57 * Return the DER encoding of the object, null if the DER encoding can not be made. 58 * 59 * @return a DER byte array, null otherwise. 60 */ 61 public byte[] getDEREncoded() 62 { 63 try 64 { 65 return this.getEncoded(DER); 66 } 67 catch (IOException e) 68 { 69 return null; 70 } 71 } 72 73 public int hashCode() 74 { 75 return this.toASN1Object().hashCode(); 76 } 77 78 public boolean equals( 79 Object o) 80 { 81 if (this == o) 82 { 83 return true; 84 } 85 86 if (!(o instanceof DEREncodable)) 87 { 88 return false; 89 } 90 91 DEREncodable other = (DEREncodable)o; 92 93 return this.toASN1Object().equals(other.getDERObject()); 94 } 95 96 public DERObject getDERObject() 97 { 98 return this.toASN1Object(); 99 } 100 101 public abstract DERObject toASN1Object(); 102 } 103