CMSEnvelopedDataStreamGenerator.cs
8.13 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
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
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Cms
{
/**
* General class for generating a CMS enveloped-data message stream.
* <p>
* A simple example of usage.
* <pre>
* CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();
*
* edGen.AddKeyTransRecipient(cert);
*
* MemoryStream bOut = new MemoryStream();
*
* Stream out = edGen.Open(
* bOut, CMSEnvelopedDataGenerator.AES128_CBC);*
* out.Write(data);
*
* out.Close();
* </pre>
* </p>
*/
public class CmsEnvelopedDataStreamGenerator
: CmsEnvelopedGenerator
{
private object _originatorInfo = null;
private object _unprotectedAttributes = null;
private int _bufferSize;
private bool _berEncodeRecipientSet;
public CmsEnvelopedDataStreamGenerator()
{
}
/// <summary>Constructor allowing specific source of randomness</summary>
/// <param name="rand">Instance of <c>SecureRandom</c> to use.</param>
public CmsEnvelopedDataStreamGenerator(
SecureRandom rand)
: base(rand)
{
}
/// <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)
{
_bufferSize = bufferSize;
}
/// <summary>Use a BER Set to store the recipient information.</summary>
public void SetBerEncodeRecipients(
bool berEncodeRecipientSet)
{
_berEncodeRecipientSet = berEncodeRecipientSet;
}
private DerInteger Version
{
get
{
int version = (_originatorInfo != null || _unprotectedAttributes != null)
? 2
: 0;
return new DerInteger(version);
}
}
/// <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);
Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);
ICipherParameters cipherParameters;
AlgorithmIdentifier encAlgID = GetAlgorithmIdentifier(
encryptionOid, encKey, asn1Params, out cipherParameters);
Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
{
try
{
recipientInfos.Add(rig.Generate(encKey, rand));
}
catch (InvalidKeyException e)
{
throw new CmsException("key inappropriate for algorithm.", e);
}
catch (GeneralSecurityException e)
{
throw new CmsException("error making encrypted content.", e);
}
}
return Open(outStream, encAlgID, cipherParameters, recipientInfos);
}
private Stream Open(
Stream outStream,
AlgorithmIdentifier encAlgID,
ICipherParameters cipherParameters,
Asn1EncodableVector recipientInfos)
{
try
{
//
// ContentInfo
//
BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);
cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);
//
// Encrypted Data
//
BerSequenceGenerator envGen = new BerSequenceGenerator(
cGen.GetRawOutputStream(), 0, true);
envGen.AddObject(this.Version);
Stream envRaw = envGen.GetRawOutputStream();
Asn1Generator recipGen = _berEncodeRecipientSet
? (Asn1Generator) new BerSetGenerator(envRaw)
: new DerSetGenerator(envRaw);
foreach (Asn1Encodable ae in recipientInfos)
{
recipGen.AddObject(ae);
}
recipGen.Close();
BerSequenceGenerator eiGen = new BerSequenceGenerator(envRaw);
eiGen.AddObject(CmsObjectIdentifiers.Data);
eiGen.AddObject(encAlgID);
Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
eiGen.GetRawOutputStream(), 0, false, _bufferSize);
IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.Algorithm);
cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));
CipherStream cOut = new CipherStream(octetOutputStream, null, cipher);
return new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen);
}
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);
}
}
/**
* generate an enveloped object that contains an CMS Enveloped Data object
* @throws IOException
*/
public Stream Open(
Stream outStream,
string encryptionOid)
{
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));
return Open(outStream, encryptionOid, keyGen);
}
/**
* generate an enveloped object that contains an CMS Enveloped Data object
* @throws IOException
*/
public Stream Open(
Stream outStream,
string encryptionOid,
int keySize)
{
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
keyGen.Init(new KeyGenerationParameters(rand, keySize));
return Open(outStream, encryptionOid, keyGen);
}
private class CmsEnvelopedDataOutputStream
: BaseOutputStream
{
private readonly CmsEnvelopedGenerator _outer;
private readonly CipherStream _out;
private readonly BerSequenceGenerator _cGen;
private readonly BerSequenceGenerator _envGen;
private readonly BerSequenceGenerator _eiGen;
public CmsEnvelopedDataOutputStream(
CmsEnvelopedGenerator outer,
CipherStream outStream,
BerSequenceGenerator cGen,
BerSequenceGenerator envGen,
BerSequenceGenerator eiGen)
{
_outer = outer;
_out = outStream;
_cGen = cGen;
_envGen = envGen;
_eiGen = eiGen;
}
public override void WriteByte(
byte b)
{
_out.WriteByte(b);
}
public override void Write(
byte[] bytes,
int off,
int len)
{
_out.Write(bytes, off, len);
}
#if PORTABLE
protected override void Dispose(bool disposing)
{
if (disposing)
{
Platform.Dispose(_out);
// TODO Parent context(s) should really be closed explicitly
_eiGen.Close();
if (_outer.unprotectedAttributeGenerator != null)
{
Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());
Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector());
_envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs));
}
_envGen.Close();
_cGen.Close();
}
base.Dispose(disposing);
}
#else
public override void Close()
{
Platform.Dispose(_out);
// TODO Parent context(s) should really be closed explicitly
_eiGen.Close();
if (_outer.unprotectedAttributeGenerator != null)
{
Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());
Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector());
_envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs));
}
_envGen.Close();
_cGen.Close();
base.Close();
}
#endif
}
}
}