summary refs log tree commit diff
path: root/crypto/src/asn1/DerBitString.cs
blob: caa97933fb73de42dc08e525ba4a97107f672f9f (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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
using System;
using System.Diagnostics;
using System.IO;
using System.Text;

using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Asn1
{
	public class DerBitString
		: DerStringBase, Asn1BitStringParser
    {
        internal class Meta : Asn1UniversalType
        {
            internal static readonly Asn1UniversalType Instance = new Meta();

            private Meta() : base(typeof(DerBitString), Asn1Tags.BitString) { }

            internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString)
            {
                return CreatePrimitive(octetString.GetOctets());
            }

            internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence)
            {
                return sequence.ToAsn1BitString();
            }
        }

        private static readonly char[] table
			= { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        /**
		 * return a Bit string from the passed in object
		 *
		 * @exception ArgumentException if the object cannot be converted.
		 */
		public static DerBitString GetInstance(object obj)
		{
            if (obj == null)
                return null;

			if (obj is DerBitString derBitString)
				return derBitString;

            if (obj is IAsn1Convertible asn1Convertible)
            {
                Asn1Object asn1Object = asn1Convertible.ToAsn1Object();
                if (asn1Object is DerBitString converted)
                    return converted;
            }
            else if (obj is byte[] bytes)
            {
                try
                {
                    return GetInstance(FromByteArray(bytes));
                }
                catch (IOException e)
                {
                    throw new ArgumentException("failed to construct BIT STRING from byte[]: " + e.Message);
                }
            }

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

		/**
		 * return a Bit string from a tagged object.
		 *
		 * @param obj the tagged object holding the object we want
		 * @param explicitly true if the object is meant to be explicitly
		 *              tagged false otherwise.
		 * @exception ArgumentException if the tagged object cannot
		 *               be converted.
		 */
        public static DerBitString GetInstance(Asn1TaggedObject obj, bool isExplicit)
        {
            return (DerBitString)Meta.Instance.GetContextInstance(obj, isExplicit);
        }

        internal readonly byte[] contents;

        public DerBitString(byte data, int padBits)
        {
            if (padBits > 7 || padBits < 0)
                throw new ArgumentException("pad bits cannot be greater than 7 or less than 0", "padBits");

            this.contents = new byte[] { (byte)padBits, data };
        }

        public DerBitString(byte[] data)
            : this(data, 0)
        {
        }

        /**
		 * @param data the octets making up the bit string.
		 * @param padBits the number of extra bits at the end of the string.
		 */
        public DerBitString(byte[] data, int padBits)
		{
            if (data == null)
                throw new ArgumentNullException("data");
            if (padBits < 0 || padBits > 7)
                throw new ArgumentException("must be in the range 0 to 7", "padBits");
            if (data.Length == 0 && padBits != 0)
                throw new ArgumentException("if 'data' is empty, 'padBits' must be 0");

            this.contents = Arrays.Prepend(data, (byte)padBits);
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public DerBitString(ReadOnlySpan<byte> data)
            : this(data, 0)
        {
        }

        public DerBitString(ReadOnlySpan<byte> data, int padBits)
        {
            if (padBits < 0 || padBits > 7)
                throw new ArgumentException("must be in the range 0 to 7", "padBits");
            if (data.IsEmpty && padBits != 0)
                throw new ArgumentException("if 'data' is empty, 'padBits' must be 0");

            this.contents = Arrays.Prepend(data, (byte)padBits);
        }
#endif

        public DerBitString(int namedBits)
        {
            if (namedBits == 0)
            {
                this.contents = new byte[]{ 0 };
                return;
            }

            int bits = 32 - Integers.NumberOfLeadingZeros(namedBits);
            int bytes = (bits + 7) / 8;
            Debug.Assert(0 < bytes && bytes <= 4);

            byte[] data = new byte[1 + bytes];

            for (int i = 1; i < bytes; i++)
            {
                data[i] = (byte)namedBits;
                namedBits >>= 8;
            }

            Debug.Assert((namedBits & 0xFF) != 0);
            data[bytes] = (byte)namedBits;

            int padBits = 0;
            while ((namedBits & (1 << padBits)) == 0)
            {
                ++padBits;
            }

            Debug.Assert(padBits < 8);
            data[0] = (byte)padBits;

            this.contents = data;
        }

        public DerBitString(Asn1Encodable obj)
            : this(obj.GetDerEncoded())
		{
		}

        internal DerBitString(byte[] contents, bool check)
        {
            if (check)
            {
                if (null == contents)
                    throw new ArgumentNullException("contents");
                if (contents.Length < 1)
                    throw new ArgumentException("cannot be empty", "contents");

                int padBits = contents[0];
                if (padBits > 0)
                {
                    if (contents.Length < 2)
                        throw new ArgumentException("zero length data with non-zero pad bits", "contents");
                    if (padBits > 7)
                        throw new ArgumentException("pad bits cannot be greater than 7 or less than 0", "contents");
                }
            }

            this.contents = contents;
        }

        /**
         * Return the octets contained in this BIT STRING, checking that this BIT STRING really
         * does represent an octet aligned string. Only use this method when the standard you are
         * following dictates that the BIT STRING will be octet aligned.
         *
         * @return a copy of the octet aligned data.
         */
        public virtual byte[] GetOctets()
        {
            if (contents[0] != 0)
                throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING");

            return Arrays.CopyOfRange(contents, 1, contents.Length);
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        internal ReadOnlyMemory<byte> GetOctetsMemory()
        {
            if (contents[0] != 0)
                throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING");

            return contents.AsMemory(1);
        }

        internal ReadOnlySpan<byte> GetOctetsSpan()
        {
            if (contents[0] != 0)
                throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING");

            return contents.AsSpan(1);
        }
#endif

        public virtual byte[] GetBytes()
		{
            if (contents.Length == 1)
                return Asn1OctetString.EmptyOctets;

            int padBits = contents[0];
            byte[] rv = Arrays.CopyOfRange(contents, 1, contents.Length);
            // DER requires pad bits be zero
            rv[rv.Length - 1] &= (byte)(0xFF << padBits);
            return rv;
        }

        public virtual int PadBits
		{
			get { return contents[0]; }
		}

		/**
		 * @return the value of the bit string as an int (truncating if necessary)
		 */
        public virtual int IntValue
		{
			get
			{
                int value = 0, end = System.Math.Min(5, contents.Length - 1);
                for (int i = 1; i < end; ++i)
                {
                    value |= (int)contents[i] << (8 * (i - 1));
                }
                if (1 <= end && end < 5)
                {
                    int padBits = contents[0];
                    byte der = (byte)(contents[end] & (0xFF << padBits));
                    value |= (int)der << (8 * (end - 1));
                }
                return value;
            }
		}

        internal override IAsn1Encoding GetEncoding(int encoding)
        {
            int padBits = contents[0];
            if (padBits != 0)
            {
                int last = contents.Length - 1;
                byte lastBer = contents[last];
                byte lastDer = (byte)(lastBer & (0xFF << padBits));

                if (lastBer != lastDer)
                    return new PrimitiveEncodingSuffixed(Asn1Tags.Universal, Asn1Tags.BitString, contents, lastDer);
            }

            return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.BitString, contents);
        }

        internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo)
        {
            int padBits = contents[0];
            if (padBits != 0)
            {
                int last = contents.Length - 1;
                byte lastBer = contents[last];
                byte lastDer = (byte)(lastBer & (0xFF << padBits));

                if (lastBer != lastDer)
                    return new PrimitiveEncodingSuffixed(tagClass, tagNo, contents, lastDer);
            }

            return new PrimitiveEncoding(tagClass, tagNo, contents);
        }

        internal sealed override DerEncoding GetEncodingDer()
        {
            int padBits = contents[0];
            if (padBits != 0)
            {
                int last = contents.Length - 1;
                byte lastBer = contents[last];
                byte lastDer = (byte)(lastBer & (0xFF << padBits));

                if (lastBer != lastDer)
                    return new PrimitiveDerEncodingSuffixed(Asn1Tags.Universal, Asn1Tags.BitString, contents, lastDer);
            }

            return new PrimitiveDerEncoding(Asn1Tags.Universal, Asn1Tags.BitString, contents);
        }

        internal sealed override DerEncoding GetEncodingDerImplicit(int tagClass, int tagNo)
        {
            int padBits = contents[0];
            if (padBits != 0)
            {
                int last = contents.Length - 1;
                byte lastBer = contents[last];
                byte lastDer = (byte)(lastBer & (0xFF << padBits));

                if (lastBer != lastDer)
                    return new PrimitiveDerEncodingSuffixed(tagClass, tagNo, contents, lastDer);
            }

            return new PrimitiveDerEncoding(tagClass, tagNo, contents);
        }

        protected override int Asn1GetHashCode()
		{
            if (contents.Length < 2)
                return 1;

            int padBits = contents[0];
            int last = contents.Length - 1;

            byte lastDer = (byte)(contents[last] & (0xFF << padBits));

            int hc = Arrays.GetHashCode(contents, 0, last);
            hc *= 257;
            hc ^= lastDer;
            return hc;
        }

        protected override bool Asn1Equals(Asn1Object asn1Object)
		{
            DerBitString that = asn1Object as DerBitString;
            if (null == that)
                return false;

            byte[] thisContents = this.contents, thatContents = that.contents;

            int length = thisContents.Length;
            if (thatContents.Length != length)
                return false;
            if (length == 1)
                return true;

            int last = length - 1;
            for (int i = 0; i < last; ++i)
            {
                if (thisContents[i] != thatContents[i])
                    return false;
            }

            int padBits = thisContents[0];
            byte thisLastDer = (byte)(thisContents[last] & (0xFF << padBits));
            byte thatLastDer = (byte)(thatContents[last] & (0xFF << padBits));

            return thisLastDer == thatLastDer;
        }

        public Stream GetBitStream()
        {
            return new MemoryStream(contents, 1, contents.Length - 1, false);
        }

        public Stream GetOctetStream()
        {
            int padBits = contents[0] & 0xFF;
            if (0 != padBits)
                throw new IOException("expected octet-aligned bitstring, but found padBits: " + padBits);

            return GetBitStream();
        }

        public Asn1BitStringParser Parser
        {
            get { return this; }
        }

        public override string GetString()
		{
			byte[] str = GetDerEncoded();

            StringBuilder buffer = new StringBuilder(1 + str.Length * 2);
            buffer.Append('#');

            for (int i = 0; i != str.Length; i++)
			{
				uint u8 = str[i];
				buffer.Append(table[u8 >> 4]);
				buffer.Append(table[u8 & 0xF]);
			}

			return buffer.ToString();
		}

		internal static DerBitString CreatePrimitive(byte[] contents)
		{
            int length = contents.Length;
            if (length < 1)
                throw new ArgumentException("truncated BIT STRING detected", "contents");

            int padBits = contents[0];
            if (padBits > 0)
            {
                if (padBits > 7 || length < 2)
                    throw new ArgumentException("invalid pad bits detected", "contents");

                byte finalOctet = contents[length - 1];
                if (finalOctet != (byte)(finalOctet & (0xFF << padBits)))
                    return new DLBitString(contents, false);
            }

            return new DerBitString(contents, false);
		}
	}
}