mirrored from https://www.bouncycastle.org/repositories/bc-csharp
-
Notifications
You must be signed in to change notification settings - Fork 602
Expand file tree
/
Copy pathBERGenerator.cs
More file actions
116 lines (102 loc) · 3.21 KB
/
Copy pathBERGenerator.cs
File metadata and controls
116 lines (102 loc) · 3.21 KB
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
using System;
using System.IO;
using Org.BouncyCastle.Utilities.IO;
namespace Org.BouncyCastle.Asn1
{
public abstract class BerGenerator
: Asn1Generator
{
private bool _tagged = false;
private bool _isExplicit;
private int _tagNo;
protected BerGenerator(Stream outStream)
: base(outStream)
{
}
protected BerGenerator(Stream outStream, int tagNo, bool isExplicit)
: base(outStream)
{
_tagged = true;
_isExplicit = isExplicit;
_tagNo = tagNo;
}
protected override void Finish()
{
WriteBerEnd();
}
public override void AddObject(Asn1Encodable obj)
{
obj.EncodeTo(OutStream);
}
public override void AddObject(Asn1Object obj)
{
obj.EncodeTo(OutStream);
}
public override Stream GetRawOutputStream()
{
return OutStream;
}
private void WriteHdr(int tag)
{
OutStream.WriteByte((byte)tag);
OutStream.WriteByte(0x80);
}
private void WriteHdr(int flags, int tagNo)
{
Asn1OutputStream.WriteIdentifier(OutStream, flags, tagNo);
OutStream.WriteByte(0x80);
}
protected void WriteBerHeader(int tag)
{
if (!_tagged)
{
WriteHdr(tag);
}
else if (_isExplicit)
{
/*
* X.690-0207 8.14.2. If implicit tagging [..] was not used [..], the encoding shall be constructed
* and the contents octets shall be the complete base encoding.
*/
WriteHdr(Asn1Tags.ContextSpecific | Asn1Tags.Constructed, _tagNo);
WriteHdr(tag);
}
else
{
/*
* X.690-0207 8.14.3. If implicit tagging was used [..], then: a) the encoding shall be constructed
* if the base encoding is constructed, and shall be primitive otherwise; and b) the contents octets
* shall be [..] the contents octets of the base encoding.
*/
WriteHdr(InheritConstructedFlag(Asn1Tags.ContextSpecific, tag), _tagNo);
}
}
// TODO[api] Remove unnecessary method
protected void WriteBerBody(Stream contentStream)
{
Streams.PipeAll(contentStream, OutStream);
}
protected void WriteBerEnd()
{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
Span<byte> data = stackalloc byte[4]{ 0x00, 0x00, 0x00, 0x00 };
if (_tagged && _isExplicit) // write extra end for tag header
{
OutStream.Write(data[..4]);
}
else
{
OutStream.Write(data[..2]);
}
#else
OutStream.WriteByte(0x00);
OutStream.WriteByte(0x00);
if (_tagged && _isExplicit) // write extra end for tag header
{
OutStream.WriteByte(0x00);
OutStream.WriteByte(0x00);
}
#endif
}
}
}