1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.asn1.der;
19
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22
23 /***
24 * DER TaggedObject
25 */
26 public class DERTaggedObject implements DEREncodable
27 {
28 protected int tag;
29 protected boolean empty = false;
30 protected boolean explicit = true;
31 protected DEREncodable obj;
32 private byte[] bytes;
33
34 /***
35 * create an implicitly tagged object that contains a zero
36 * length sequence.
37 */
38 public DERTaggedObject( int tag )
39 {
40 this( false, tag, new DERSequence() );
41 }
42
43 /***
44 * @param tag the tag number for this object.
45 * @param obj the tagged object.
46 */
47 public DERTaggedObject( int tag, DEREncodable obj )
48 {
49 this.explicit = true;
50 this.tag = tag;
51 this.obj = obj;
52 }
53
54 /***
55 * @param explicit true if an explicitly tagged object.
56 * @param tag the tag number for this object.
57 * @param obj the tagged object.
58 */
59 public DERTaggedObject( boolean explicit, int tag, DEREncodable obj )
60 {
61 this.explicit = explicit;
62 this.tag = tag;
63 this.obj = obj;
64 }
65
66 public DERTaggedObject( boolean explicit, int tag, DEREncodable obj, byte[] bytes )
67 {
68 this.explicit = explicit;
69 this.tag = tag;
70 this.obj = obj;
71 this.bytes = bytes;
72 }
73
74 public byte[] getOctets()
75 {
76 return bytes;
77 }
78
79 public int getTagNo()
80 {
81 return tag;
82 }
83
84 /***
85 * return whatever was following the tag.
86 * <p>
87 * Note: tagged objects are generally context dependent if you're
88 * trying to extract a tagged object you should be going via the
89 * appropriate getInstance method.
90 */
91 public DEREncodable getObject()
92 {
93 if ( obj != null )
94 {
95 return obj;
96 }
97
98 return null;
99 }
100
101 public void encode( ASN1OutputStream out ) throws IOException
102 {
103 if ( !empty )
104 {
105 ByteArrayOutputStream baos = new ByteArrayOutputStream();
106 ASN1OutputStream aos = new ASN1OutputStream( baos );
107
108 aos.writeObject( obj );
109 aos.close();
110
111 byte[] bytes = baos.toByteArray();
112
113 if ( explicit )
114 {
115 out.writeEncoded( DERObject.CONSTRUCTED | DERObject.TAGGED | tag, bytes );
116 }
117 else
118 {
119
120 if ( ( bytes[ 0 ] & DERObject.CONSTRUCTED ) != 0 )
121 {
122 bytes[ 0 ] = (byte) ( DERObject.CONSTRUCTED | DERObject.TAGGED | tag );
123 }
124 else
125 {
126 bytes[ 0 ] = (byte) ( DERObject.TAGGED | tag );
127 }
128
129 out.write( bytes );
130 }
131 }
132 else
133 {
134 out.writeEncoded( DERObject.CONSTRUCTED | DERObject.TAGGED | tag, new byte[ 0 ] );
135 }
136 }
137 }