summary refs log tree commit diff
path: root/crypto/src/asn1/Asn1OutputStream.cs
blob: 7dd1f78832818402d1ca4e476efff8fcc416f69a (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
using System;
using System.Diagnostics;
using System.IO;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
using System.Buffers.Binary;
using System.Numerics;
#endif

using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Asn1
{
    public class Asn1OutputStream
        : FilterStream
    {
        internal const int EncodingBer = 1;
        internal const int EncodingDL = 2;
        internal const int EncodingDer = 3;

        public static Asn1OutputStream Create(Stream output)
        {
            return new Asn1OutputStream(output, false);
        }

        public static Asn1OutputStream Create(Stream output, string encoding)
        {
            return Create(output, encoding, false);
        }

        public static Asn1OutputStream Create(Stream output, string encoding, bool leaveOpen)
        {
            if (Asn1Encodable.Der.Equals(encoding))
                return new DerOutputStream(output, leaveOpen);
            if (Asn1Encodable.DL.Equals(encoding))
                return new DLOutputStream(output, leaveOpen);
            return new Asn1OutputStream(output, leaveOpen);
        }

        internal static int GetEncodingType(string encoding)
        {
            if (Asn1Encodable.Der.Equals(encoding))
                return EncodingDer;
            if (Asn1Encodable.DL.Equals(encoding))
                return EncodingDL;
            return EncodingBer;
        }

        private readonly bool m_leaveOpen;

        protected internal Asn1OutputStream(Stream output, bool leaveOpen)
            : base(output)
        {
            if (!output.CanWrite)
                throw new ArgumentException("Expected stream to be writable", nameof(output));

            m_leaveOpen = leaveOpen;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                FlushInternal();
            }

            if (m_leaveOpen)
            {
                base.Detach(disposing);
            }
            else
            {
                base.Dispose(disposing);
            }
        }

        public virtual void WriteObject(Asn1Encodable asn1Encodable)
        {
            if (null == asn1Encodable)
                throw new ArgumentNullException("asn1Encodable");

            asn1Encodable.ToAsn1Object().GetEncoding(this.Encoding).Encode(this);
            FlushInternal();
        }

        public virtual void WriteObject(Asn1Object asn1Object)
        {
            if (null == asn1Object)
                throw new ArgumentNullException("asn1Object");

            asn1Object.GetEncoding(this.Encoding).Encode(this);
            FlushInternal();
        }

        internal void EncodeContents(IAsn1Encoding[] contentsEncodings)
        {
            for (int i = 0, count = contentsEncodings.Length; i < count; ++i)
            {
                contentsEncodings[i].Encode(this);
            }
        }

        internal virtual int Encoding
        {
            get { return EncodingBer; }
        }

        private void FlushInternal()
        {
            // Placeholder to support future internal buffering
        }

        internal void WriteDL(int dl)
        {
            if (dl < 128)
            {
                Debug.Assert(dl >= 0);
                WriteByte((byte)dl);
                return;
            }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            Span<byte> encoding = stackalloc byte[5];
            BinaryPrimitives.WriteUInt32BigEndian(encoding[1..], (uint)dl);
            int leadingZeroBytes = BitOperations.LeadingZeroCount((uint)dl) / 8;
            encoding[leadingZeroBytes] = (byte)(0x84 - leadingZeroBytes);
            Write(encoding[leadingZeroBytes..]);
#else
            byte[] stack = new byte[5];
            int pos = stack.Length;

            do
            {
                stack[--pos] = (byte)dl;
                dl >>= 8;
            }
            while (dl > 0);

            int count = stack.Length - pos;
            stack[--pos] = (byte)(0x80 | count);

            Write(stack, pos, count + 1);
#endif
        }

        internal void WriteIdentifier(int flags, int tagNo)
        {
            if (tagNo < 31)
            {
                WriteByte((byte)(flags | tagNo));
                return;
            }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            Span<byte> stack = stackalloc byte[6];
#else
            byte[] stack = new byte[6];
#endif
            int pos = stack.Length;

            stack[--pos] = (byte)(tagNo & 0x7F);
            while (tagNo > 127)
            {
                tagNo >>= 7;
                stack[--pos] = (byte)(tagNo & 0x7F | 0x80);
            }

            stack[--pos] = (byte)(flags | 0x1F);

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            Write(stack[pos..]);
#else
            Write(stack, pos, stack.Length - pos);
#endif
        }

        internal static IAsn1Encoding[] GetContentsEncodings(int encoding, Asn1Encodable[] elements)
        {
            int count = elements.Length;
            IAsn1Encoding[] contentsEncodings = new IAsn1Encoding[count];
            for (int i = 0; i < count; ++i)
            {
                contentsEncodings[i] = elements[i].ToAsn1Object().GetEncoding(encoding);
            }
            return contentsEncodings;
        }

        internal static DerEncoding[] GetContentsEncodingsDer(Asn1Encodable[] elements)
        {
            int count = elements.Length;
            DerEncoding[] contentsEncodings = new DerEncoding[count];
            for (int i = 0; i < count; ++i)
            {
                contentsEncodings[i] = elements[i].ToAsn1Object().GetEncodingDer();
            }
            return contentsEncodings;
        }

        internal static int GetLengthOfContents(IAsn1Encoding[] contentsEncodings)
        {
            int contentsLength = 0;
            for (int i = 0, count = contentsEncodings.Length; i < count; ++i)
            {
                contentsLength += contentsEncodings[i].GetLength();
            }
            return contentsLength;
        }

        internal static int GetLengthOfDL(int dl)
        {
            if (dl < 128)
                return 1;

            int length = 2;
            while ((dl >>= 8) > 0)
            {
                ++length;
            }
            return length;
        }

        internal static int GetLengthOfEncodingDL(int tagNo, int contentsLength)
        {
            return GetLengthOfIdentifier(tagNo) + GetLengthOfDL(contentsLength) + contentsLength;
        }

        internal static int GetLengthOfEncodingIL(int tagNo, IAsn1Encoding contentsEncoding)
        {
            return GetLengthOfIdentifier(tagNo) + 3 + contentsEncoding.GetLength();
        }

        internal static int GetLengthOfEncodingIL(int tagNo, IAsn1Encoding[] contentsEncodings)
        {
            return GetLengthOfIdentifier(tagNo) + 3 + GetLengthOfContents(contentsEncodings);
        }

        internal static int GetLengthOfIdentifier(int tagNo)
        {
            if (tagNo < 31)
                return 1;

            int length = 2;
            while ((tagNo >>= 7) > 0)
            {
                ++length;
            }
            return length;
        }
    }
}