summary refs log tree commit diff
path: root/crypto/src/asn1/Asn1TaggedObject.cs
blob: aaa719ecca3aadd586fad2fa08fdd1d9662ab9f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
using System;
using System.IO;

using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Asn1
{
    /**
     * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
     * a [n] where n is some number - these are assumed to follow the construction
     * rules (as with sequences).
     */
    public abstract class Asn1TaggedObject
		: Asn1Object, Asn1TaggedObjectParser
    {
        // TODO[asn1] Rewrite DerApplicationSpecific in terms of Asn1TaggedObject and remove this
        internal static bool IsConstructed(bool isExplicit, Asn1Object obj)
        {
            if (isExplicit || obj is Asn1Sequence || obj is Asn1Set)
                return true;
            Asn1TaggedObject tagged = obj as Asn1TaggedObject;
            if (tagged == null)
                return false;
            return IsConstructed(tagged.IsExplicit(), tagged.GetObject());
        }

		public static Asn1TaggedObject GetInstance(object obj)
		{
            if (obj == null || obj is Asn1TaggedObject) 
            {
                return (Asn1TaggedObject)obj;
            }
            //else if (obj is Asn1TaggedObjectParser)
            else if (obj is IAsn1Convertible)
            {
                Asn1Object asn1Object = ((IAsn1Convertible)obj).ToAsn1Object();
                if (asn1Object is Asn1TaggedObject)
                    return (Asn1TaggedObject)asn1Object;
            }
            else if (obj is byte[])
            {
                try
                {
                    return CheckedCast(FromByteArray((byte[])obj));
                }
                catch (IOException e)
                {
                    throw new ArgumentException("failed to construct tagged object from byte[]: " + e.Message);
                }
            }

            throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj");
		}

        public static Asn1TaggedObject GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit)
        {
            if (Asn1Tags.ContextSpecific != taggedObject.TagClass)
                throw new InvalidOperationException("this method only valid for CONTEXT_SPECIFIC tags");

            if (!declaredExplicit)
                throw new ArgumentException("this method not valid for implicitly tagged tagged objects");

            return taggedObject.GetExplicitBaseTagged();
        }

        internal readonly int tagClass = Asn1Tags.ContextSpecific;
        internal readonly int tagNo;
        internal readonly bool explicitly;
        internal readonly Asn1Encodable obj;

        /**
         * @param tagNo the tag number for this object.
         * @param obj the tagged object.
         */
        protected Asn1TaggedObject(int tagNo, Asn1Encodable obj)
            : this(true, tagNo, obj)
        {
        }

		/**
         * @param explicitly true if the object is explicitly tagged.
         * @param tagNo the tag number for this object.
         * @param obj the tagged object.
         */
        protected Asn1TaggedObject(bool explicitly, int tagNo, Asn1Encodable obj)
        {
            if (null == obj)
                throw new ArgumentNullException("obj");

            // IAsn1Choice marker interface 'insists' on explicit tagging
            this.explicitly = explicitly || (obj is IAsn1Choice);
            this.tagNo = tagNo;
            this.obj = obj;
        }

		protected override bool Asn1Equals(Asn1Object asn1Object)
        {
            if (asn1Object is DerApplicationSpecific)
                return asn1Object.CallAsn1Equals(this);

            Asn1TaggedObject that = asn1Object as Asn1TaggedObject;
            return null != that
                && this.tagClass == that.tagClass
                && this.tagNo == that.tagNo
                && this.explicitly == that.explicitly   // TODO Should this be part of equality?
                && this.GetObject().Equals(that.GetObject());
		}

		protected override int Asn1GetHashCode()
		{
            int code = (tagClass * 7919) ^ tagNo;

			// TODO: actually this is wrong - the problem is that a re-encoded
			// object may end up with a different hashCode due to implicit
			// tagging. As implicit tagging is ambiguous if a sequence is involved
			// it seems the only correct method for both equals and hashCode is to
			// compare the encodings...
//			code ^= explicitly.GetHashCode();

            code ^= obj.GetHashCode();

			return code;
        }

        public int TagClass
        {
            get { return tagClass; }
        }

		public int TagNo
        {
			get { return tagNo; }
        }

        public bool HasContextTag(int tagNo)
        {
            return this.tagClass == Asn1Tags.ContextSpecific && this.tagNo == tagNo;
        }

        public bool HasTag(int tagClass, int tagNo)
        {
            return this.tagClass == tagClass && this.tagNo == tagNo;
        }

        /**
         * return whether or not the object may be explicitly tagged.
         * <p>
         * Note: if the object has been read from an input stream, the only
         * time you can be sure if isExplicit is returning the true state of
         * affairs is if it returns false. An implicitly tagged object may appear
         * to be explicitly tagged, so you need to understand the context under
         * which the reading was done as well, see GetObject below.</p>
         */
        public bool IsExplicit()
        {
            return explicitly;
        }

        [Obsolete("Will be removed. Replace with constant return value of 'false'")]
        public bool IsEmpty()
        {
            return false;
        }

        /**
         * Return the contents of this object as a byte[]
         *
         * @return the encoded contents of the object.
         */
        // TODO Need this public if/when DerApplicationSpecific extends Asn1TaggedObject
        internal byte[] GetContents()
        {
            try
            {
                byte[] baseEncoding = obj.GetEncoded(Asn1Encoding);
                if (IsExplicit())
                    return baseEncoding;

                MemoryStream input = new MemoryStream(baseEncoding, false);
                int tag = input.ReadByte();
                Asn1InputStream.ReadTagNumber(input, tag);
                int length = Asn1InputStream.ReadLength(input, (int)(input.Length - input.Position), false);
                int remaining = (int)(input.Length - input.Position);

                // For indefinite form, account for end-of-contents octets
                int contentsLength = length < 0 ? remaining - 2 : remaining;
                if (contentsLength < 0)
                    throw new InvalidOperationException("failed to get contents");

                byte[] contents = new byte[contentsLength];
                Array.Copy(baseEncoding, baseEncoding.Length - remaining, contents, 0, contentsLength);
                return contents;
            }
            catch (IOException e)
            {
                throw new InvalidOperationException("failed to get contents", e);
            }
        }

        /**
         * return whatever was following the tag.
         * <p>
         * Note: tagged objects are generally context dependent if you're
         * trying to extract a tagged object you should be going via the
         * appropriate GetInstance method.</p>
         */
        public Asn1Object GetObject()
        {
            if (Asn1Tags.ContextSpecific != TagClass)
                throw new InvalidOperationException("this method only valid for CONTEXT_SPECIFIC tags");

            return obj.ToAsn1Object();
        }

        /**
         * Needed for open types, until we have better type-guided parsing support. Use sparingly for other
         * purposes, and prefer {@link #getExplicitBaseTagged()}, {@link #getImplicitBaseTagged(int, int)} or
         * {@link #getBaseUniversal(boolean, int)} where possible. Before using, check for matching tag
         * {@link #getTagClass() class} and {@link #getTagNo() number}.
         */
        public Asn1Encodable GetBaseObject()
        {
            return obj;
        }

        /**
         * Needed for open types, until we have better type-guided parsing support. Use
         * sparingly for other purposes, and prefer {@link #getExplicitBaseTagged()} or
         * {@link #getBaseUniversal(boolean, int)} where possible. Before using, check
         * for matching tag {@link #getTagClass() class} and {@link #getTagNo() number}.
         */
        public Asn1Encodable GetExplicitBaseObject()
        {
            if (!IsExplicit())
                throw new InvalidOperationException("object implicit - explicit expected.");

            return obj;
        }

        public Asn1TaggedObject GetExplicitBaseTagged()
        {
            if (!IsExplicit())
                throw new InvalidOperationException("object implicit - explicit expected.");

            return CheckedCast(obj.ToAsn1Object());
        }

        /**
		* Return the object held in this tagged object as a parser assuming it has
		* the type of the passed in tag. If the object doesn't have a parser
		* associated with it, the base object is returned.
		*/
        public IAsn1Convertible GetObjectParser(int tag, bool isExplicit)
		{
            if (Asn1Tags.ContextSpecific != TagClass)
                throw new InvalidOperationException("this method only valid for CONTEXT_SPECIFIC tags");

            switch (tag)
			{
            //case Asn1Tags.BitString:
            //    return Asn1BitString.GetInstance(this, isExplicit).Parser;
            case Asn1Tags.OctetString:
                return Asn1OctetString.GetInstance(this, isExplicit).Parser;
            case Asn1Tags.Sequence:
                return Asn1Sequence.GetInstance(this, isExplicit).Parser;
            case Asn1Tags.Set:
				return Asn1Set.GetInstance(this, isExplicit).Parser;
			}

			if (isExplicit)
			{
				return GetObject();
			}

			throw Platform.CreateNotImplementedException("implicit tagging for tag: " + tag);
		}

		public override string ToString()
		{
            return Asn1Utilities.GetTagText(tagClass, tagNo) + obj;
		}

        internal abstract string Asn1Encoding { get; }

        internal abstract Asn1Sequence RebuildConstructed(Asn1Object asn1Object);

        internal static Asn1Object CreateConstructed(int tagClass, int tagNo, bool isIL,
            Asn1EncodableVector contentsElements)
        {
            bool maybeExplicit = (contentsElements.Count == 1);

            if (isIL)
            {
                if (Asn1Tags.Application == tagClass)
                    return new BerApplicationSpecific(tagNo, contentsElements);

                return maybeExplicit
                    ? new BerTaggedObject(true, tagNo, contentsElements[0])
                    : new BerTaggedObject(false, tagNo, BerSequence.FromVector(contentsElements));
            }

            if (Asn1Tags.Application == tagClass)
                return new DerApplicationSpecific(tagNo, contentsElements);

            return maybeExplicit
                ? new DLTaggedObject(true, tagNo, contentsElements[0])
                : new DLTaggedObject(false, tagNo, DLSequence.FromVector(contentsElements));
        }

        internal static Asn1Object CreatePrimitive(int tagClass, int tagNo, byte[] contentsOctets)
        {
            // Note: !CONSTRUCTED => IMPLICIT
            if (Asn1Tags.Application == tagClass)
                return new DerApplicationSpecific(false, tagNo, contentsOctets);

            return new DLTaggedObject(false, tagNo, new DerOctetString(contentsOctets));
        }

        private static Asn1TaggedObject CheckedCast(Asn1Object asn1Object)
        {
            Asn1TaggedObject taggedObject = asn1Object as Asn1TaggedObject;
            if (null != taggedObject)
                return taggedObject;

            throw new InvalidOperationException("unexpected object: " + Platform.GetTypeName(asn1Object));
        }
    }
}