summary refs log tree commit diff
path: root/crypto/src/cms/CMSEnvelopedHelper.cs
blob: 888aba817b9ecaebb6be445cbcd222e84a602d83 (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
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
{
	class CmsEnvelopedHelper
	{
		internal static readonly CmsEnvelopedHelper Instance = new CmsEnvelopedHelper();

		private static readonly IDictionary<string, int> KeySizes = new Dictionary<string, int>();
		private static readonly IDictionary<string, string> BaseCipherNames = new Dictionary<string, string>();

		static CmsEnvelopedHelper()
		{
			KeySizes.Add(CmsEnvelopedGenerator.DesEde3Cbc, 192);
			KeySizes.Add(CmsEnvelopedGenerator.Aes128Cbc, 128);
			KeySizes.Add(CmsEnvelopedGenerator.Aes192Cbc, 192);
			KeySizes.Add(CmsEnvelopedGenerator.Aes256Cbc, 256);

			BaseCipherNames.Add(CmsEnvelopedGenerator.DesEde3Cbc,  "DESEDE");
			BaseCipherNames.Add(CmsEnvelopedGenerator.Aes128Cbc,  "AES");
			BaseCipherNames.Add(CmsEnvelopedGenerator.Aes192Cbc,  "AES");
			BaseCipherNames.Add(CmsEnvelopedGenerator.Aes256Cbc,  "AES");
		}

		private string GetAsymmetricEncryptionAlgName(
			string encryptionAlgOid)
		{
			if (Asn1.Pkcs.PkcsObjectIdentifiers.RsaEncryption.Id.Equals(encryptionAlgOid))
			{
				return "RSA/ECB/PKCS1Padding";
			}

			return encryptionAlgOid;
		}

		internal IBufferedCipher CreateAsymmetricCipher(
			string encryptionOid)
		{
			string asymName = GetAsymmetricEncryptionAlgName(encryptionOid);
			if (!asymName.Equals(encryptionOid))
			{
				try
				{
					return CipherUtilities.GetCipher(asymName);
				}
				catch (SecurityUtilityException)
				{
					// Ignore
				}
			}
			return CipherUtilities.GetCipher(encryptionOid);
		}

		internal IWrapper CreateWrapper(
			string encryptionOid)
		{
			try
			{
				return WrapperUtilities.GetWrapper(encryptionOid);
			}
			catch (SecurityUtilityException)
			{
				return WrapperUtilities.GetWrapper(GetAsymmetricEncryptionAlgName(encryptionOid));
			}
		}

		internal string GetRfc3211WrapperName(string oid)
		{
			if (oid == null)
				throw new ArgumentNullException(nameof(oid));

			if (!BaseCipherNames.TryGetValue(oid, out var alg))
				throw new ArgumentException("no name for " + oid, nameof(oid));

			return alg + "RFC3211Wrap";
		}

		internal int GetKeySize(string oid)
		{
			if (oid == null)
				throw new ArgumentNullException(nameof(oid));

			if (!KeySizes.TryGetValue(oid, out var keySize))
				throw new ArgumentException("no keysize for " + oid, "oid");

			return keySize;
		}

		internal static RecipientInformationStore BuildRecipientInformationStore(
			Asn1Set recipientInfos, CmsSecureReadable secureReadable)
		{
			var infos = new List<RecipientInformation>();
			for (int i = 0; i != recipientInfos.Count; i++)
			{
				RecipientInfo info = RecipientInfo.GetInstance(recipientInfos[i]);

				ReadRecipientInfo(infos, info, secureReadable);
			}
			return new RecipientInformationStore(infos);
		}

		private static void ReadRecipientInfo(IList<RecipientInformation> infos, RecipientInfo info,
			CmsSecureReadable secureReadable)
		{
			Asn1Encodable recipInfo = info.Info;
			if (recipInfo is KeyTransRecipientInfo keyTransRecipientInfo)
			{
				infos.Add(new KeyTransRecipientInformation(keyTransRecipientInfo, secureReadable));
			}
			else if (recipInfo is KekRecipientInfo kekRecipientInfo)
			{
				infos.Add(new KekRecipientInformation(kekRecipientInfo, secureReadable));
			}
			else if (recipInfo is KeyAgreeRecipientInfo keyAgreeRecipientInfo)
			{
				KeyAgreeRecipientInformation.ReadRecipientInfo(infos, keyAgreeRecipientInfo, secureReadable);
			}
			else if (recipInfo is PasswordRecipientInfo passwordRecipientInfo)
			{
				infos.Add(new PasswordRecipientInformation(passwordRecipientInfo, secureReadable));
			}
		}

		internal class CmsAuthenticatedSecureReadable : CmsSecureReadable
		{
			private AlgorithmIdentifier algorithm;
			private IMac mac;
			private CmsReadable readable;

			internal CmsAuthenticatedSecureReadable(AlgorithmIdentifier algorithm, CmsReadable readable)
			{
				this.algorithm = algorithm;
				this.readable = readable;
			}

			public AlgorithmIdentifier Algorithm
			{
				get { return this.algorithm; }
			}

			public object CryptoObject
			{
				get { return this.mac; }
			}

			public CmsReadable GetReadable(KeyParameter sKey)
			{
                string macAlg = this.algorithm.Algorithm.Id;
//				Asn1Object sParams = this.algorithm.Parameters.ToAsn1Object();

				try
				{
					this.mac = MacUtilities.GetMac(macAlg);

					// FIXME Support for MAC algorithm parameters similar to cipher parameters
//						ASN1Object sParams = (ASN1Object)macAlg.getParameters();
//
//						if (sParams != null && !(sParams instanceof ASN1Null))
//						{
//							AlgorithmParameters params = CMSEnvelopedHelper.INSTANCE.createAlgorithmParameters(macAlg.getObjectId().getId(), provider);
//
//							params.init(sParams.getEncoded(), "ASN.1");
//
//							mac.init(sKey, params.getParameterSpec(IvParameterSpec.class));
//						}
//						else
					{
						mac.Init(sKey);
					}

//						Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();
//
//						ICipherParameters cipherParameters = sKey;
//
//						if (asn1Params != null && !(asn1Params is Asn1Null))
//						{
//							cipherParameters = ParameterUtilities.GetCipherParameters(
//							macAlg.Algorithm, cipherParameters, asn1Params);
//						}
//						else
//						{
//							string alg = macAlg.Algorithm.Id;
//							if (alg.Equals(CmsEnvelopedGenerator.DesEde3Cbc)
//								|| alg.Equals(CmsEnvelopedGenerator.IdeaCbc)
//								|| alg.Equals(CmsEnvelopedGenerator.Cast5Cbc))
//							{
//								cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
//							}
//						}
//
//						mac.Init(cipherParameters);
				}
				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("error decoding algorithm parameters.", e);
				}

				try
				{
					return new CmsProcessableInputStream(
						new TeeInputStream(
							readable.GetInputStream(),
							new MacSink(this.mac)));
				}
				catch (IOException e)
				{
					throw new CmsException("error reading content.", e);
				}
			}
		}

		internal class CmsEnvelopedSecureReadable : CmsSecureReadable
		{
			private AlgorithmIdentifier algorithm;
			private IBufferedCipher cipher;
			private CmsReadable readable;

			internal CmsEnvelopedSecureReadable(AlgorithmIdentifier algorithm, CmsReadable readable)
			{
				this.algorithm = algorithm;
				this.readable = readable;
			}

			public AlgorithmIdentifier Algorithm
			{
				get { return this.algorithm; }
			}

			public object CryptoObject
			{
				get { return this.cipher; }
			}

			public CmsReadable GetReadable(KeyParameter sKey)
			{
				try
				{
                    this.cipher = CipherUtilities.GetCipher(this.algorithm.Algorithm);

					Asn1Encodable asn1Enc = this.algorithm.Parameters;
					Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();

					ICipherParameters cipherParameters = sKey;

					if (asn1Params != null && !(asn1Params is Asn1Null))
					{
						cipherParameters = ParameterUtilities.GetCipherParameters(
                            this.algorithm.Algorithm, cipherParameters, asn1Params);
					}
					else
					{
                        string alg = this.algorithm.Algorithm.Id;
						if (alg.Equals(CmsEnvelopedGenerator.DesEde3Cbc)
							|| alg.Equals(CmsEnvelopedGenerator.IdeaCbc)
							|| alg.Equals(CmsEnvelopedGenerator.Cast5Cbc))
						{
							cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
						}
					}

					cipher.Init(false, cipherParameters);
				}
				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("error decoding algorithm parameters.", e);
				}

				try
				{
					return new CmsProcessableInputStream(
						new CipherStream(readable.GetInputStream(), cipher, null));
				}
				catch (IOException e)
				{
					throw new CmsException("error reading content.", e);
				}
			}
		}
	}
}