-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcustomcrypto.cs
More file actions
411 lines (376 loc) · 15.4 KB
/
customcrypto.cs
File metadata and controls
411 lines (376 loc) · 15.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
// This class creates a custom crytographic object based on the asymmetric
// algorithm by extending the abstract base class AsymmetricAlgorithm.
//<Snippet2>
using System;
using System.Xml;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
[assembly: AssemblyKeyFile("CustomCrypto.snk")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: CLSCompliant(true)]
namespace Contoso
{
// Define a CustomCrypto class that inherits from the AsymmetricAlgorithm
// class.
public class CustomCrypto :
System.Security.Cryptography.AsymmetricAlgorithm
{
// Declare local member variables.
private CspParameters cspParameters;
private readonly KeySizes[] keySizes = {new KeySizes(8, 64, 8)};
// Initialize a CustomCrypto with the default key size of 8.
public CustomCrypto()
{
this.KeySize = 8;
}
// Initialize a CustomCrypto with the specified key size.
public CustomCrypto(int keySize)
{
this.KeySize = keySize;
}
// Accessor function for keySizes member variable.
public override KeySizes[] LegalKeySizes
{
get { return (KeySizes[])keySizes.Clone(); }
}
// Modify the KeySizeValue property inherited from the Asymmetric
// class. Prior to setting the value, ensure it falls within the
// range identified in the local keySizes member variable.
//<Snippet9>
public override int KeySize
{
get { return KeySizeValue; }
set
{
for (int i=0; i < keySizes.Length; i++)
{
if (keySizes[i].SkipSize == 0)
{
if (keySizes[i].MinSize == value)
{
KeySizeValue = value;
return;
}
}
else
{
for (int j = keySizes[i].MinSize;
j <= keySizes[i].MaxSize;
j += keySizes[i].SkipSize)
{
if (j == value)
{
KeySizeValue = value;
return;
}
}
}
}
// If the key does not fall within the range identified
// in the keySizes member variable, throw an exception.
throw new CryptographicException("Invalid key size.");
}
}
//</Snippet9>
// Initialize the parameters with default values.
public void InitializeParameters()
{
cspParameters = new CspParameters();
cspParameters.ProviderName = "Contoso";
cspParameters.KeyContainerName = "SecurityBin1";
cspParameters.KeyNumber = 1;
cspParameters.ProviderType = 2;
}
// Parse specified xmlString for values to populate the CspParams
//<Snippet4>
// Expected XML schema:
// <CustomCryptoKeyValue>
// <ProviderName></ProviderName>
// <KeyContainerName></KeyContainerName>
// <KeyNumber></KeyNumber>
// <ProviderType></ProviderType>
// </CustomCryptoKeyValue>
public override void FromXmlString(string xmlString)
{
if (xmlString != null)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNode firstNode = doc.FirstChild;
XmlNodeList nodeList;
// Assemble parameters from values in each XML element.
cspParameters = new CspParameters();
// KeyContainerName is optional.
nodeList = doc.GetElementsByTagName("KeyContainerName");
string keyName = nodeList.Item(0).InnerText;
if (keyName != null)
{
cspParameters.KeyContainerName = keyName;
}
// KeyNumber is optional.
nodeList = doc.GetElementsByTagName("KeyNumber");
string keyNumber = nodeList.Item(0).InnerText;
if (keyNumber != null)
{
cspParameters.KeyNumber = Int32.Parse(keyNumber);
}
// ProviderName is optional.
nodeList = doc.GetElementsByTagName("ProviderName");
string providerName = nodeList.Item(0).InnerText;
if (providerName != null)
{
cspParameters.ProviderName = providerName;
}
// ProviderType is optional.
nodeList = doc.GetElementsByTagName("ProviderType");
string providerType = nodeList.Item(0).InnerText;
if (providerType != null)
{
cspParameters.ProviderType = Int32.Parse(providerType);
}
}
else
{
throw new ArgumentNullException("xmlString");
}
}
//</Snippet4>
// Create an XML string representation of the parameters in the
// current customCrypto object.
//<Snippet5>
public override string ToXmlString(bool includePrivateParameters)
{
string keyContainerName = "";
string keyNumber = "";
string providerName = "";
string providerType = "";
if (cspParameters != null)
{
keyContainerName = cspParameters.KeyContainerName;
keyNumber = cspParameters.KeyNumber.ToString();
providerName = cspParameters.ProviderName;
providerType = cspParameters.ProviderType.ToString();
}
StringBuilder sb = new StringBuilder();
sb.Append("<CustomCryptoKeyValue>");
sb.Append("<KeyContainerName>");
sb.Append(keyContainerName);
sb.Append("</KeyContainerName>");
sb.Append("<KeyNumber>");
sb.Append(keyNumber);
sb.Append("</KeyNumber>");
sb.Append("<ProviderName>");
sb.Append(providerName);
sb.Append("</ProviderName>");
sb.Append("<ProviderType>");
sb.Append(providerType);
sb.Append("</ProviderType>");
sb.Append("</CustomCryptoKeyValue>");
return(sb.ToString());
}
//</Snippet5>
// Return the name for the key exchange algorithm.
//<Snippet6>
public override string KeyExchangeAlgorithm
{
get {return "RSA-PKCS1-KeyEx";}
}
//</Snippet6>
// Retrieves the name of the signature alogrithm.
//<Snippet7>
// This example uses the SHA1 algorithm.
// Due to collision problems with SHA1, Microsoft recommends using a NIST-approved hash function.
public override string SignatureAlgorithm
{
get {return "http://www.w3.org/2000/09/xmldsig#rsa-sha1";}
}
//</Snippet7>
// Required member for implementing the AsymmetricAlgorithm class.
protected override void Dispose(bool disposing) {}
// Call the Create method using the CustomCrypto assembly name.
//<Snippet11>
// The create function attempts to create a CustomCrypto object using
// the assembly name. This functionality requires modification of the
// machine.config file. Add the following section to the configuration
// element and modify the values of the cryptoClass to reflect what is
// installed in your machines GAC.
//<mscorlib>
// <cryptographySettings>
// <cryptoNameMapping>
// <cryptoClasses>
// <cryptoClass CustomCrypto="Contoso.CustomCrypto,
// CustomCrypto,
// Culture=neutral,
// PublicKeyToken=fdb9f9c4851028bf,
// Version=1.0.1448.27640" />
// </cryptoClasses>
// <nameEntry name="Contoso.CustomCrypto" class="CustomCrypto" />
// <nameEntry name="CustomCrypto" class="CustomCrypto" />
// </cryptoNameMapping>
// </cryptographySettings>
//</mscorlib>
new static public CustomCrypto Create()
{
return Create("CustomCrypto");
}
//</Snippet11>
// Create a CustomCrypto object by calling CrytoConfig's
// CreateFromName method and casting the type to CustomCrypto.
//<Snippet12>
// The create function attempts to create a CustomCrypto object using
// the assembly name. This functionality requires modification of the
// machine.config file. Add the following section to the configuration
// element and modify the values of the cryptoClass to reflect what is
// installed in your machines GAC.
//<mscorlib>
// <cryptographySettings>
// <cryptoNameMapping>
// <cryptoClasses>
// <cryptoClass CustomCrypto="Contoso.CustomCrypto,
// CustomCrypto,
// Culture=neutral,
// PublicKeyToken=fdb9f9c4851028bf,
// Version=1.0.1448.27640" />
// </cryptoClasses>
// <nameEntry name="Contoso.CustomCrypto" class="CustomCrypto" />
// <nameEntry name="CustomCrypto" class="CustomCrypto" />
// </cryptoNameMapping>
// </cryptographySettings>
//</mscorlib>
new static public CustomCrypto Create(String algorithmName)
{
return (CustomCrypto) CryptoConfig.CreateFromName(algorithmName);
}
//</Snippet12>
}
//<Snippet3>
class CustomCryptoImpl
{
[STAThread]
static void Main(string[] args)
{
// Construct a CustomCrypto object and initialize its
// CspParameters.
CustomCrypto customCrypto = new CustomCrypto();
customCrypto.InitializeParameters();
// Display properties of the current customCrypto object.
Console.WriteLine("*** CustomCrypto created with default " +
"parameters:");
DisplayProperties(customCrypto);
// Release all the resources used by this instance of
// CustomCrytpo.
//<Snippet1>
customCrypto.Clear();
//</Snippet1>
customCrypto = new CustomCrypto(64);
// Create new parameters and set them by using the FromXmlString
// method.
string parameterXml = "<CustomCryptoKeyValue>";
parameterXml += "<ProviderName>Contoso</ProviderName>";
parameterXml += "<KeyContainerName>SecurityBin2";
parameterXml += "</KeyContainerName>";
parameterXml += "<KeyNumber>1</KeyNumber>";
parameterXml += "<ProviderType>2</ProviderType>";
parameterXml += "</CustomCryptoKeyValue>";
customCrypto.FromXmlString(parameterXml);
// Display the properties of a customCrypto object created with
// custom parameters.
Console.WriteLine("\n*** " +
"CustomCrypto created with custom parameters:");
DisplayProperties(customCrypto);
// Create an object by using the assembly name.
try
{
CustomCrypto myCryptoA = CustomCrypto.Create("CustomCrypto");
if (myCryptoA != null)
{
Console.Write("\n*** " +
"Successfully created CustomCrytpo from");
Console.WriteLine(" the Create method.");
DisplayProperties(myCryptoA);
}
else
{
Console.Write("Unable to create CustomCrytpo from ");
Console.WriteLine(" the Create method.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine("This sample completed successfully; " +
"press Enter to exit.");
Console.ReadLine();
}
// Display the properties of the specified CustomCrypto object to the
// console.
public static void DisplayProperties(CustomCrypto customCrypto)
{
try
{
// Retrieve the class description for the customCrypto object.
//<Snippet8>
string classDescription = customCrypto.ToString();
//</Snippet8>
Console.WriteLine(classDescription);
Console.Write("KeyExchangeAlgorithm: ");
Console.WriteLine(customCrypto.KeyExchangeAlgorithm);
Console.Write("SignatureAlgorithm: ");
Console.WriteLine(customCrypto.SignatureAlgorithm);
Console.WriteLine("KeySize: " + customCrypto.KeySize);
Console.WriteLine("Parameters described in Xml format:");
Console.WriteLine(customCrypto.ToXmlString(true));
// Display the MinSize, MaxSize, and SkipSize properties of
// each KeySize item in the local keySizes member variable.
//<Snippet10>
KeySizes[] legalKeySizes = customCrypto.LegalKeySizes;
if (legalKeySizes.Length > 0)
{
for (int i=0; i < legalKeySizes.Length; i++)
{
Console.Write("Keysize" + i + " min, max, step: ");
Console.Write(legalKeySizes[i].MinSize + ", ");
Console.Write(legalKeySizes[i].MaxSize + ", ");
Console.WriteLine(legalKeySizes[i].SkipSize + ", ");
}
}
//</Snippet10>
}
catch (Exception ex)
{
Console.WriteLine("Caught unexpected exception: " +
ex.ToString());
}
}
}
}
//
// This sample produces the following output:
//
// *** CustomCrypto created with default parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 8
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin1</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8,
//
// *** CustomCrypto created with custom parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 64
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin2</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8,
// Unable to create CustomCrytpo from the Create method
// This sample completed successfully; press Exit to continue.
//</Snippet3>
//</Snippet2>