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 pathParameterUtilities.cs
More file actions
519 lines (463 loc) · 22.4 KB
/
Copy pathParameterUtilities.cs
File metadata and controls
519 lines (463 loc) · 22.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
using System;
using System.Collections.Generic;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Misc;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Nsri;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Security
{
/// <summary>
/// Helpers for building <see cref="ICipherParameters"/> values: creating algorithm-appropriate
/// <see cref="KeyParameter"/> instances, decoding ASN.1 algorithm parameters into IV-bearing
/// <see cref="ICipherParameters"/>, generating random IV/parameter blocks, and wrapping/unwrapping
/// <see cref="ParametersWithRandom"/> / <see cref="ParametersWithContext"/> envelopes.
/// </summary>
/// <remarks>
/// Algorithm names are resolved through <see cref="GetCanonicalAlgorithmName"/> and matched
/// case-insensitively. DES, DES-EDE and RC2 receive their dedicated parameter subclasses with parity
/// enforcement; other algorithms get a plain <see cref="KeyParameter"/>.
/// </remarks>
public static class ParameterUtilities
{
private static readonly Dictionary<string, string> Algorithms =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, int> BasicIVSizes =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
static ParameterUtilities()
{
AddAlgorithm("AES",
"AESWRAP");
AddAlgorithm("AES128",
SecurityUtilities.WrongAes128,
NistObjectIdentifiers.IdAes128Cbc,
NistObjectIdentifiers.IdAes128Ccm,
NistObjectIdentifiers.IdAes128Cfb,
NistObjectIdentifiers.IdAes128Ecb,
NistObjectIdentifiers.IdAes128Gcm,
NistObjectIdentifiers.IdAes128Ofb,
NistObjectIdentifiers.IdAes128Wrap,
NistObjectIdentifiers.IdAes128WrapPad);
AddAlgorithm("AES192",
SecurityUtilities.WrongAes192,
NistObjectIdentifiers.IdAes192Cbc,
NistObjectIdentifiers.IdAes192Ccm,
NistObjectIdentifiers.IdAes192Cfb,
NistObjectIdentifiers.IdAes192Ecb,
NistObjectIdentifiers.IdAes192Gcm,
NistObjectIdentifiers.IdAes192Ofb,
NistObjectIdentifiers.IdAes192Wrap,
NistObjectIdentifiers.IdAes192WrapPad);
AddAlgorithm("AES256",
SecurityUtilities.WrongAes256,
NistObjectIdentifiers.IdAes256Cbc,
NistObjectIdentifiers.IdAes256Ccm,
NistObjectIdentifiers.IdAes256Cfb,
NistObjectIdentifiers.IdAes256Ecb,
NistObjectIdentifiers.IdAes256Gcm,
NistObjectIdentifiers.IdAes256Ofb,
NistObjectIdentifiers.IdAes256Wrap,
NistObjectIdentifiers.IdAes256WrapPad);
AddAlgorithm("ARIA");
AddAlgorithm("ARIA128",
NsriObjectIdentifiers.id_aria128_cbc,
NsriObjectIdentifiers.id_aria128_ccm,
NsriObjectIdentifiers.id_aria128_cfb,
NsriObjectIdentifiers.id_aria128_ctr,
NsriObjectIdentifiers.id_aria128_ecb,
NsriObjectIdentifiers.id_aria128_gcm,
NsriObjectIdentifiers.id_aria128_kw,
NsriObjectIdentifiers.id_aria128_kwp,
NsriObjectIdentifiers.id_aria128_ocb2,
NsriObjectIdentifiers.id_aria128_ofb);
AddAlgorithm("ARIA192",
NsriObjectIdentifiers.id_aria192_cbc,
NsriObjectIdentifiers.id_aria192_ccm,
NsriObjectIdentifiers.id_aria192_cfb,
NsriObjectIdentifiers.id_aria192_ctr,
NsriObjectIdentifiers.id_aria192_ecb,
NsriObjectIdentifiers.id_aria192_gcm,
NsriObjectIdentifiers.id_aria192_kw,
NsriObjectIdentifiers.id_aria192_kwp,
NsriObjectIdentifiers.id_aria192_ocb2,
NsriObjectIdentifiers.id_aria192_ofb);
AddAlgorithm("ARIA256",
NsriObjectIdentifiers.id_aria256_cbc,
NsriObjectIdentifiers.id_aria256_ccm,
NsriObjectIdentifiers.id_aria256_cfb,
NsriObjectIdentifiers.id_aria256_ctr,
NsriObjectIdentifiers.id_aria256_ecb,
NsriObjectIdentifiers.id_aria256_gcm,
NsriObjectIdentifiers.id_aria256_kw,
NsriObjectIdentifiers.id_aria256_kwp,
NsriObjectIdentifiers.id_aria256_ocb2,
NsriObjectIdentifiers.id_aria256_ofb);
AddAlgorithm("BLOWFISH",
/*
* TODO[api] Incorrect version of cryptlib_algorithm_blowfish_CBC
* Remove at major version update and delete bad test data "pbes2.bf-cbc.key"
*/
"1.3.6.1.4.1.3029.1.2",
MiscObjectIdentifiers.cryptlib_algorithm_blowfish_CBC);
AddAlgorithm("CAMELLIA",
"CAMELLIAWRAP");
AddAlgorithm("CAMELLIA128",
NttObjectIdentifiers.IdCamellia128Cbc,
NttObjectIdentifiers.IdCamellia128Wrap);
AddAlgorithm("CAMELLIA192",
NttObjectIdentifiers.IdCamellia192Cbc,
NttObjectIdentifiers.IdCamellia192Wrap);
AddAlgorithm("CAMELLIA256",
NttObjectIdentifiers.IdCamellia256Cbc,
NttObjectIdentifiers.IdCamellia256Wrap);
AddAlgorithm("CAST5",
MiscObjectIdentifiers.cast5CBC);
AddAlgorithm("CAST6");
AddAlgorithm("CHACHA");
AddAlgorithm("CHACHA7539",
"CHACHA20",
"CHACHA20-POLY1305",
PkcsObjectIdentifiers.IdAlgAeadChaCha20Poly1305);
AddAlgorithm("XCHACHA20",
"XCHACHA20-POLY1305");
AddAlgorithm("DES",
OiwObjectIdentifiers.DesCbc,
OiwObjectIdentifiers.DesCfb,
OiwObjectIdentifiers.DesEcb,
OiwObjectIdentifiers.DesOfb);
AddAlgorithm("DESEDE",
"DESEDEWRAP",
"TDEA",
OiwObjectIdentifiers.DesEde,
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc);
AddAlgorithm("GOST28147",
"GOST",
"GOST-28147",
CryptoProObjectIdentifiers.GostR28147Gcfb);
AddAlgorithm("HC128");
AddAlgorithm("HC256");
AddAlgorithm("IDEA",
MiscObjectIdentifiers.as_sys_sec_alg_ideaCBC);
AddAlgorithm("NOEKEON");
AddAlgorithm("RC2",
PkcsObjectIdentifiers.RC2Cbc,
PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
AddAlgorithm("RC4",
"ARC4",
PkcsObjectIdentifiers.rc4);
AddAlgorithm("RC5",
"RC5-32");
AddAlgorithm("RC5-64");
AddAlgorithm("RC6");
AddAlgorithm("RIJNDAEL");
AddAlgorithm("SALSA20");
AddAlgorithm("SEED",
KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
KisaObjectIdentifiers.IdSeedCbc);
AddAlgorithm("SERPENT");
AddAlgorithm("SKIPJACK");
AddAlgorithm("SM4");
AddAlgorithm("TEA");
AddAlgorithm("THREEFISH-256");
AddAlgorithm("THREEFISH-512");
AddAlgorithm("THREEFISH-1024");
AddAlgorithm("TNEPRES");
AddAlgorithm("TWOFISH");
AddAlgorithm("VMPC");
AddAlgorithm("VMPC-KSA3");
AddAlgorithm("XTEA");
AddBasicIVSizeEntries(8, "BLOWFISH", "CHACHA", "DES", "DESEDE", "DESEDE3", "SALSA20");
AddBasicIVSizeEntries(12, "CHACHA7539");
AddBasicIVSizeEntries(16, "AES", "AES128", "AES192", "AES256", "ARIA", "ARIA128", "ARIA192", "ARIA256",
"CAMELLIA", "CAMELLIA128", "CAMELLIA192", "CAMELLIA256", "NOEKEON", "SEED", "SM4");
AddBasicIVSizeEntries(24, "XCHACHA20");
// TODO These algorithms support an IV
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// "RIJNDAEL", "SKIPJACK", "TWOFISH"
}
private static void AddAlgorithm(string canonicalName, params object[] aliases)
{
Algorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
Algorithms[alias.ToString()] = canonicalName;
}
}
private static void AddBasicIVSizeEntries(int size, params string[] algorithms)
{
foreach (string algorithm in algorithms)
{
BasicIVSizes.Add(algorithm, size);
}
}
/// <summary>
/// Returns the canonical algorithm name for the given alias or OID string, or <c>null</c> if the
/// algorithm is not recognised.
/// </summary>
public static string GetCanonicalAlgorithmName(string algorithm)
{
return CollectionUtilities.GetValueOrNull(Algorithms, algorithm);
}
/// <summary>
/// Build a <see cref="KeyParameter"/> for the algorithm identified by <paramref name="algOid"/>.
/// </summary>
public static KeyParameter CreateKeyParameter(DerObjectIdentifier algOid, byte[] keyBytes)
{
return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length);
}
/// <summary>Build a <see cref="KeyParameter"/> for the named algorithm.</summary>
public static KeyParameter CreateKeyParameter(string algorithm, byte[] keyBytes)
{
return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length);
}
/// <summary>Build a <see cref="KeyParameter"/> from a slice of <paramref name="keyBytes"/>.</summary>
public static KeyParameter CreateKeyParameter(DerObjectIdentifier algOid, byte[] keyBytes, int offset,
int length)
{
return CreateKeyParameter(algOid.Id, keyBytes, offset, length);
}
/// <summary>
/// Build a <see cref="KeyParameter"/> from a slice of <paramref name="keyBytes"/>. DES / DES-EDE / RC2
/// keys are returned as their dedicated parameter subclasses; all other algorithms get a plain
/// <see cref="KeyParameter"/>.
/// </summary>
/// <exception cref="ArgumentNullException">If <paramref name="algorithm"/> is <c>null</c>.</exception>
/// <exception cref="SecurityUtilityException">If the algorithm is not recognised.</exception>
public static KeyParameter CreateKeyParameter(string algorithm, byte[] keyBytes, int offset, int length)
{
if (algorithm == null)
throw new ArgumentNullException(nameof(algorithm));
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
if (canonical == "DES")
return new DesParameters(keyBytes, offset, length);
if (canonical == "DESEDE" || canonical == "DESEDE3")
return new DesEdeParameters(keyBytes, offset, length);
if (canonical == "RC2")
return new RC2Parameters(keyBytes, offset, length);
return new KeyParameter(keyBytes, offset, length);
}
/// <summary>
/// Combine a key with ASN.1-encoded algorithm parameters, returning the appropriate
/// <see cref="ICipherParameters"/> envelope (e.g. <see cref="ParametersWithIV"/> or
/// <see cref="AeadParameters"/> for AES-GCM/CCM).
/// </summary>
public static ICipherParameters GetCipherParameters(DerObjectIdentifier algOid, ICipherParameters key,
Asn1Object asn1Params)
{
return GetCipherParameters(algOid.Id, key, asn1Params);
}
/// <summary>
/// Combine a key with ASN.1-encoded algorithm parameters for the named algorithm. See the OID
/// overload.
/// </summary>
/// <exception cref="ArgumentException">If <paramref name="key"/> cannot supply the data required by
/// an AEAD mode, or the parameters block cannot be parsed.</exception>
/// <exception cref="SecurityUtilityException">If the algorithm is not recognised.</exception>
public static ICipherParameters GetCipherParameters(string algorithm, ICipherParameters key,
Asn1Object asn1Params)
{
if (algorithm == null)
throw new ArgumentNullException(nameof(algorithm));
if (DerObjectIdentifier.TryFromID(algorithm, out var algOid))
{
if (algOid.On(NistObjectIdentifiers.Aes))
{
if (NistObjectIdentifiers.IdAes128Gcm.Equals(algOid) ||
NistObjectIdentifiers.IdAes192Gcm.Equals(algOid) ||
NistObjectIdentifiers.IdAes256Gcm.Equals(algOid))
{
if (!(key is KeyParameter keyParameter))
throw new ArgumentException("key data must be accessible for GCM operation");
var gcmParameters = GcmParameters.GetInstance(asn1Params);
return new AeadParameters(keyParameter, gcmParameters.IcvLen * 8, gcmParameters.GetNonce());
}
if (NistObjectIdentifiers.IdAes128Ccm.Equals(algOid) ||
NistObjectIdentifiers.IdAes192Ccm.Equals(algOid) ||
NistObjectIdentifiers.IdAes256Ccm.Equals(algOid))
{
if (!(key is KeyParameter keyParameter))
throw new ArgumentException("key data must be accessible for CCM operation");
var ccmParameters = CcmParameters.GetInstance(asn1Params);
return new AeadParameters(keyParameter, ccmParameters.IcvLen * 8, ccmParameters.GetNonce());
}
}
}
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
Asn1OctetString iv = null;
try
{
// TODO These algorithms support an IV
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// "RIJNDAEL", "SKIPJACK", "TWOFISH"
int basicIVKeySize = FindBasicIVSize(canonical);
if (basicIVKeySize != -1
|| canonical == "RIJNDAEL" || canonical == "SKIPJACK" || canonical == "TWOFISH")
{
iv = Asn1OctetString.GetInstance(asn1Params);
}
else if (canonical == "CAST5")
{
iv = Cast5CbcParameters.GetInstance(asn1Params).IV;
}
else if (canonical == "IDEA")
{
iv = IdeaCbcPar.GetInstance(asn1Params).IV;
}
else if (canonical == "RC2")
{
iv = RC2CbcParameter.GetInstance(asn1Params).IV;
}
}
catch (Exception e)
{
throw new ArgumentException("Could not process ASN.1 parameters", e);
}
if (iv != null)
{
return new ParametersWithIV(key, iv.GetOctets());
}
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
/// <summary>
/// Generate a fresh ASN.1-encoded algorithm parameters block (typically a random IV) for the
/// algorithm identified by <paramref name="algID"/>.
/// </summary>
public static Asn1Encodable GenerateParameters(DerObjectIdentifier algID, SecureRandom random)
{
return GenerateParameters(algID.Id, random);
}
/// <summary>
/// Generate a fresh ASN.1-encoded algorithm parameters block for the named algorithm. CAST5, IDEA and
/// RC2 receive their dedicated parameter structures; other IV-based algorithms get a plain
/// <see cref="Asn1OctetString"/> containing the IV.
/// </summary>
/// <exception cref="ArgumentNullException">If <paramref name="algorithm"/> is <c>null</c>.</exception>
/// <exception cref="SecurityUtilityException">If the algorithm is not recognised or has no
/// parameter generator.</exception>
public static Asn1Encodable GenerateParameters(string algorithm, SecureRandom random)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
// TODO These algorithms support an IV
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// "RIJNDAEL", "SKIPJACK", "TWOFISH"
int basicIVKeySize = FindBasicIVSize(canonical);
if (basicIVKeySize != -1)
return CreateIVOctetString(random, basicIVKeySize);
if (canonical == "CAST5")
return new Cast5CbcParameters(CreateIV(random, 8), 128);
if (canonical == "IDEA")
return new IdeaCbcPar(CreateIV(random, 8));
if (canonical == "RC2")
return new RC2CbcParameter(CreateIV(random, 8));
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
/// <summary>
/// Unwrap a <see cref="ParametersWithContext"/> envelope, returning the inner parameters and copying the
/// context bytes out via <paramref name="context"/>. If the envelope is absent, <paramref name="context"/>
/// is set to <c>null</c> and the input is returned unchanged.
/// </summary>
/// <param name="cipherParameters">Parameters to inspect.</param>
/// <param name="minLen">Minimum permitted context length, inclusive.</param>
/// <param name="maxLen">Maximum permitted context length, inclusive.</param>
/// <param name="context">Receives the context bytes, or <c>null</c> if no envelope is present.</param>
/// <exception cref="ArgumentOutOfRangeException">If the context length falls outside
/// [<paramref name="minLen"/>, <paramref name="maxLen"/>].</exception>
public static ICipherParameters GetContext(ICipherParameters cipherParameters, int minLen, int maxLen,
out byte[] context)
{
if (cipherParameters is ParametersWithContext withContext)
{
int len = withContext.ContextLength;
if (len < minLen || len > maxLen)
{
var message = $"Context length must be in range [{minLen}, {maxLen}]";
throw new ArgumentOutOfRangeException(nameof(cipherParameters), len, message);
}
context = withContext.GetContext();
return withContext.Parameters;
}
context = null;
return cipherParameters;
}
/// <summary>
/// Unwrap a <see cref="ParametersWithRandom"/> envelope, returning the inner parameters and exposing the
/// attached <see cref="SecureRandom"/> via <paramref name="random"/>. If the envelope is absent,
/// <paramref name="random"/> is set to <c>null</c> and the input is returned unchanged.
/// </summary>
public static ICipherParameters GetRandom(ICipherParameters cipherParameters, out SecureRandom random)
{
if (cipherParameters is ParametersWithRandom withRandom)
{
random = withRandom.Random;
return withRandom.Parameters;
}
random = null;
return cipherParameters;
}
/// <summary>
/// Strip any <see cref="ParametersWithRandom"/> envelope and return the inner parameters; otherwise return
/// the input unchanged.
/// </summary>
public static ICipherParameters IgnoreRandom(ICipherParameters cipherParameters)
{
if (cipherParameters is ParametersWithRandom withRandom)
return withRandom.Parameters;
return cipherParameters;
}
/// <summary>
/// Wrap <paramref name="cp"/> in a <see cref="ParametersWithContext"/> envelope when <paramref name="context"/>
/// is non-<c>null</c>; otherwise return <paramref name="cp"/> unchanged.
/// </summary>
public static ICipherParameters WithContext(ICipherParameters cp, byte[] context)
{
if (context != null)
{
cp = new ParametersWithContext(cp, context);
}
return cp;
}
/// <summary>
/// Wrap <paramref name="cp"/> in a <see cref="ParametersWithRandom"/> envelope when <paramref name="random"/>
/// is non-<c>null</c>; otherwise return <paramref name="cp"/> unchanged.
/// </summary>
public static ICipherParameters WithRandom(ICipherParameters cp, SecureRandom random)
{
if (random != null)
{
cp = new ParametersWithRandom(cp, random);
}
return cp;
}
private static Asn1OctetString CreateIVOctetString(SecureRandom random, int ivLength)
{
return new DerOctetString(CreateIV(random, ivLength));
}
private static byte[] CreateIV(SecureRandom random, int ivLength)
{
return SecureRandom.GetNextBytes(random, ivLength);
}
private static int FindBasicIVSize(string canonicalName)
{
return BasicIVSizes.TryGetValue(canonicalName, out int keySize) ? keySize : -1;
}
}
}