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 pathCMSEnvelopedDataStreamGenerator.cs
More file actions
274 lines (232 loc) · 11.4 KB
/
Copy pathCMSEnvelopedDataStreamGenerator.cs
File metadata and controls
274 lines (232 loc) · 11.4 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
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
using System;
using System.Collections.Generic;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO;
namespace Org.BouncyCastle.Cms
{
/// <summary>
/// Streaming generator for CMS EnvelopedData (PKCS#7 enveloped-data) messages. Add recipients via the base
/// <see cref="CmsEnvelopedGenerator"/> methods, then call <see cref="Open(Stream, string)"/> to obtain a
/// <see cref="Stream"/> to which the content to be encrypted is written; closing that stream finalizes the
/// CMS structure.
/// </summary>
/// <remarks>
/// The returned stream must be closed (disposed) to finalize the CMS structure. Closing the returned stream
/// does <b>not</b> close the underlying stream passed to <c>Open</c>; callers are responsible for closing the
/// underlying stream separately. If the underlying stream is a buffering encoder whose tail state only flushes
/// on close (e.g. a base64 encoding stream), failing to close it will cause the encoded output to be truncated.
/// <para>A simple example of usage:</para>
/// <code>
/// CmsEnvelopedDataStreamGenerator gen = new CmsEnvelopedDataStreamGenerator();
/// gen.AddKeyTransRecipient(cert);
/// using (Stream envOut = gen.Open(bOut, CmsEnvelopedGenerator.Aes128Cbc))
/// {
/// envOut.Write(data, 0, data.Length);
/// }
/// </code>
/// </remarks>
public class CmsEnvelopedDataStreamGenerator
: CmsEnvelopedGenerator
{
private int m_bufferSize;
private bool m_berEncodeRecipientSet;
/// <summary>Creates a generator using the default randomness source.</summary>
public CmsEnvelopedDataStreamGenerator()
{
}
/// <summary>
/// Creates a generator with an explicit randomness source for key and encryption operations.
/// </summary>
/// <param name="random">The secure random to use.</param>
public CmsEnvelopedDataStreamGenerator(SecureRandom random)
: base(random)
{
}
/// <summary>Set the underlying string size for encapsulated data.</summary>
/// <param name="bufferSize">Length of octet strings to buffer the data.</param>
public void SetBufferSize(int bufferSize)
{
m_bufferSize = bufferSize;
}
/// <summary>Controls whether recipient information is stored using a BER (indefinite-length) SET.</summary>
/// <param name="berEncodeRecipientSet">
/// <c>true</c> to use a BER SET; <c>false</c> to use a DER SET (the default).
/// </param>
public void SetBerEncodeRecipients(bool berEncodeRecipientSet)
{
m_berEncodeRecipientSet = berEncodeRecipientSet;
}
/// <summary>
/// Generate an enveloped object that contains an CMS Enveloped Data
/// object using the passed in key generator.
/// </summary>
private Stream Open(Stream outStream, string encryptionOid, CipherKeyGenerator keyGen)
{
byte[] encKeyBytes = keyGen.GenerateKey();
KeyParameter encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);
#pragma warning disable CS0618 // Type or member is obsolete
Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);
AlgorithmIdentifier encAlgID = GetAlgorithmIdentifier(encryptionOid, encKey, asn1Params,
out var cipherParameters);
#pragma warning restore CS0618 // Type or member is obsolete
// TODO[cms] Do these later when we can write each one out immediately?
Asn1EncodableVector recipientInfos = new Asn1EncodableVector(recipientInfoGenerators.Count);
foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
{
try
{
recipientInfos.Add(rig.Generate(encKey, m_random));
}
catch (InvalidKeyException e)
{
throw new CmsException("key inappropriate for algorithm.", e);
}
catch (GeneralSecurityException e)
{
throw new CmsException("error making encrypted content.", e);
}
}
// TODO[cms] Add 'Open' variant(s) with 'dataType' parameter
return Open(CmsObjectIdentifiers.Data, outStream, encAlgID, cipherParameters, recipientInfos);
}
private Stream Open(DerObjectIdentifier dataType, Stream outStream, AlgorithmIdentifier encAlgID,
ICipherParameters cipherParameters, Asn1EncodableVector recipientInfos)
{
try
{
// ContentInfo
BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);
cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);
var originatorInfo = m_originatorInformation?.ToAsn1Structure();
// EnvelopedData
BerSequenceGenerator envGen = new BerSequenceGenerator(cGen.GetRawOutputStream(), 0, true);
envGen.AddObject(GetVersion(originatorInfo, recipientInfos));
CmsUtilities.AddOriginatorInfoToGenerator(envGen, originatorInfo);
CmsUtilities.AddRecipientInfosToGenerator(envGen, recipientInfos, m_berEncodeRecipientSet);
// EncryptedContentInfo
BerSequenceGenerator eciGen = new BerSequenceGenerator(envGen.GetRawOutputStream());
eciGen.AddObject(dataType);
eciGen.AddObject(encAlgID);
// encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL (EncryptedContent ::= OCTET STRING)
BerOctetStringGenerator ecGen = new BerOctetStringGenerator(eciGen.GetRawOutputStream(), 0, false);
Stream ecStream = ecGen.GetOctetOutputStream(m_bufferSize);
IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.Algorithm);
cipher.Init(true, new ParametersWithRandom(cipherParameters, m_random));
CipherStream cOut = new CipherStream(ecStream, null, cipher);
return new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eciGen, ecGen);
}
catch (SecurityUtilityException e)
{
throw new CmsException("couldn't create cipher.", e);
}
catch (InvalidKeyException e)
{
throw new CmsException("key invalid in message.", e);
}
catch (IOException e)
{
throw new CmsException("exception decoding algorithm parameters.", e);
}
}
/// <summary>
/// Opens a stream for generating a CMS EnvelopedData object, deriving a content-encryption key of the
/// algorithm's default strength.
/// </summary>
/// <param name="outStream">The stream the CMS object is written to.</param>
/// <param name="encryptionOid">The content-encryption algorithm OID.</param>
/// <returns>A stream the content to be encrypted is written to; close it to finalize the structure.</returns>
public Stream Open(Stream outStream, string encryptionOid)
{
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength));
return Open(outStream, encryptionOid, keyGen);
}
/// <summary>
/// Opens a stream for generating a CMS EnvelopedData object, deriving a content-encryption key of the
/// given size.
/// </summary>
/// <param name="outStream">The stream the CMS object is written to.</param>
/// <param name="encryptionOid">The content-encryption algorithm OID.</param>
/// <param name="keySize">The content-encryption key size, in bits.</param>
/// <returns>A stream the content to be encrypted is written to; close it to finalize the structure.</returns>
public Stream Open(Stream outStream, string encryptionOid, int keySize)
{
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
keyGen.Init(new KeyGenerationParameters(m_random, keySize));
return Open(outStream, encryptionOid, keyGen);
}
private DerInteger GetVersion(OriginatorInfo originatorInfo, Asn1EncodableVector recipientInfos)
{
var recipientInfoSet = DLSet.FromCollection(recipientInfos);
Asn1Set unprotectedAttrs = null;
if (unprotectedAttributeGenerator != null)
{
// mark unprotected attributes as non-null.
unprotectedAttrs = DLSet.Empty;
}
int version = EnvelopedData.CalculateVersion(originatorInfo, recipientInfoSet, unprotectedAttrs);
return DerInteger.ValueOf(version);
}
private class CmsEnvelopedDataOutputStream
: BaseOutputStream
{
private readonly CmsEnvelopedGenerator m_outer;
private readonly CipherStream m_out;
private readonly BerSequenceGenerator m_cGen;
private readonly BerSequenceGenerator m_envGen;
private readonly BerSequenceGenerator m_eciGen;
private readonly BerOctetStringGenerator m_ecGen;
public CmsEnvelopedDataOutputStream(CmsEnvelopedGenerator outer, CipherStream outStream, BerSequenceGenerator cGen,
BerSequenceGenerator envGen, BerSequenceGenerator eciGen, BerOctetStringGenerator ecGen)
{
m_outer = outer;
m_out = outStream;
m_cGen = cGen;
m_envGen = envGen;
m_eciGen = eciGen;
m_ecGen = ecGen;
}
public override void Write(byte[] buffer, int offset, int count)
{
m_out.Write(buffer, offset, count);
}
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
public override void Write(ReadOnlySpan<byte> buffer)
{
m_out.Write(buffer);
}
#endif
public override void WriteByte(byte value)
{
m_out.WriteByte(value);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
m_out.Dispose();
// TODO Parent context(s) should really be closed explicitly
m_ecGen.Dispose();
m_eciGen.Dispose();
if (m_outer.unprotectedAttributeGenerator != null)
{
Asn1.Cms.AttributeTable attrTable = m_outer.unprotectedAttributeGenerator.GetAttributes(
new Dictionary<CmsAttributeTableParameter, object>());
Asn1Set unprotectedAttrs = BerSet.FromCollection(attrTable);
m_envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs));
}
m_envGen.Dispose();
m_cGen.Dispose();
}
base.Dispose(disposing);
}
}
}
}