RSA加密算法是一种非对称加密算法。在公钥加密标准和电子商业中RSA被广泛使用。RSA是1977年由罗纳德•李维斯特(Ron Rivest)、阿迪•萨莫尔(Adi Shamir)和伦纳德•阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。.Net的推出,我们能够利用.Net Framework中的类提供的加密服务来保证数据安全。目前应用较为广泛的加密方法是使用RSA算法进行加密。在.Net Framework中与RSA加密算法相关的类主要有两个:RSA 类和RSACryptoServiceProvider 类。按照MSDN的说法RSA 类是“表示 RSA 算法的所有实现均从中继承的基类”,而RSACryptoServiceProvider 类是“使用加密服务提供程序 (CSP) 提供的 RSA 算法的实现执行不对称加密和解密”。另外,“表示 RSA 算法的标准参数”的RSAParameters 结构也是很重要的,它保存了RSA算法的参数。
这里具体讲述一下在C#中如何使用框架提供的RSA算法来对我们的信息加密、签名、验证签名、解密的这个几个步骤的实现

 

代码
1 using System.Security.Cryptography;
2
3 using System.Management;
4
5 using Microsoft.Win32;
6
7
8 /// <summary>
9
10 /// 生成公私钥
11
12 /// </summary>
13
14 /// <param name="PrivateKeyPath"></param>
15
16 /// <param name="PublicKeyPath"></param>
17
18 public void RSAKey(string PrivateKeyPath, string PublicKeyPath)
19
20 {
21
22 try
23
24 {
25
26 RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
27
28 this.CreatePrivateKeyXML(PrivateKeyPath, provider.ToXmlString(true));
29
30 this.CreatePublicKeyXML(PublicKeyPath, provider.ToXmlString(false));
31
32 }
33
34 catch (Exception exception)
35
36 {
37
38 throw exception;
39
40 }
41
42 }
43
44
45 /// <summary>
46
47 /// 对原始数据进行MD5加密
48
49 /// </summary>
50
51 /// <param name="m_strSource">待加密数据</param>
52
53 /// <returns>返回机密后的数据</returns>
54
55 public string GetHash(string m_strSource)
56
57 {
58
59 HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
60
61 byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
62
63 byte[] inArray = algorithm.ComputeHash(bytes);
64
65 return Convert.ToBase64String(inArray);
66
67 }
68
69 /// <summary>
70
71 /// RSA加密
72
73 /// </summary>
74
75 /// <param name="xmlPublicKey">公钥</param>
76
77 /// <param name="m_strEncryptString">MD5加密后的数据</param>
78
79 /// <returns>RSA公钥加密后的数据</returns>
80
81 public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
82
83 {
84
85 string str2;
86
87 try
88
89 {
90
91 RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
92
93 provider.FromXmlString(xmlPublicKey);
94
95 byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
96
97 str2 = Convert.ToBase64String(provider.Encrypt(bytes, false));
98
99 }
100
101 catch (Exception exception)
102
103 {
104
105 throw exception;
106
107 }
108
109 return str2;
110
111 }
112
113 /// <summary>
114
115 /// RSA解密
116
117 /// </summary>
118
119 /// <param name="xmlPrivateKey">私钥</param>
120
121 /// <param name="m_strDecryptString">待解密的数据</param>
122
123 /// <returns>解密后的结果</returns>
124
125 public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
126
127 {
128
129 string str2;
130
131 try
132
133 {
134
135 RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
136
137 provider.FromXmlString(xmlPrivateKey);
138
139 byte[] rgb = Convert.FromBase64String(m_strDecryptString);
140
141 byte[] buffer2 = provider.Decrypt(rgb, false);
142
143 str2 = new UnicodeEncoding().GetString(buffer2);
144
145 }
146
147 catch (Exception exception)
148
149 {
150
151 throw exception;
152
153 }
154
155 return str2;
156
157 }
158
159 /// <summary>
160
161 /// 对MD5加密后的密文进行签名
162
163 /// </summary>
164
165 /// <param name="p_strKeyPrivate">私钥</param>
166
167 /// <param name="m_strHashbyteSignature">MD5加密后的密文</param>
168
169 /// <returns></returns>
170
171 public string SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature)
172
173 {
174
175 byte[] rgbHash = Convert.FromBase64String(m_strHashbyteSignature);
176
177 RSACryptoServiceProvider key = new RSACryptoServiceProvider();
178
179 key.FromXmlString(p_strKeyPrivate);
180
181 RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
182
183 formatter.SetHashAlgorithm("MD5");
184
185 byte[] inArray = formatter.CreateSignature(rgbHash);
186
187 return Convert.ToBase64String(inArray);
188
189 }
190
191 /// <summary>
192
193 /// 签名验证
194
195 /// </summary>
196
197 /// <param name="p_strKeyPublic">公钥</param>
198
199 /// <param name="p_strHashbyteDeformatter">待验证的用户名</param>
200
201 /// <param name="p_strDeformatterData">注册码</param>
202
203 /// <returns></returns>
204
205 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
206
207 {
208
209 try
210
211 {
212
213 byte[] rgbHash = Convert.FromBase64String(p_strHashbyteDeformatter);
214
215 RSACryptoServiceProvider key = new RSACryptoServiceProvider();
216
217 key.FromXmlString(p_strKeyPublic);
218
219 RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
220
221 deformatter.SetHashAlgorithm("MD5");
222
223 byte[] rgbSignature = Convert.FromBase64String(p_strDeformatterData);
224
225 if (deformatter.VerifySignature(rgbHash, rgbSignature))
226
227 {
228
229 return true;
230
231 }
232
233 return false;
234
235 }
236
237 catch
238
239 {
240
241 return false;
242
243 }
244
245 }
246
247 /// <summary>
248
249 /// 获取硬盘ID
250
251 /// </summary>
252
253 /// <returns>硬盘ID</returns>
254
255 public string GetHardID()
256
257 {
258
259 string HDInfo = "";
260
261 ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
262
263 ManagementObjectCollection moc1 = cimobject1.GetInstances();
264
265 foreach (ManagementObject mo in moc1)
266
267 {
268
269 HDInfo = (string)mo.Properties["Model"].Value;
270
271 }
272
273 return HDInfo;
274
275 }
276
277 /// <summary>
278
279 /// 读注册表中指定键的值
280
281 /// </summary>
282
283 /// <param name="key">键名</param>
284
285 /// <returns>返回键值</returns>
286
287 private string ReadReg(string key)
288
289 {
290
291 string temp = "";
292
293 try
294
295 {
296
297 RegistryKey myKey = Registry.LocalMachine;
298
299 RegistryKey subKey = myKey.OpenSubKey(@"SOFTWARE\JX\Register");
300
301
302
303 temp = subKey.GetValue(key).ToString();
304
305 subKey.Close();
306
307 myKey.Close();
308
309 return temp;
310
311 }
312
313 catch (Exception)
314
315 {
316
317 throw;//可能没有此注册项;
318
319 }
320
321
322
323 }
324
325 /// <summary>
326
327 /// 创建注册表中指定的键和值
328
329 /// </summary>
330
331 /// <param name="key">键名</param>
332
333 /// <param name="value">键值</param>
334
335 private void WriteReg(string key, string value)
336
337 {
338
339 try
340
341 {
342
343 RegistryKey rootKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\JX\Register");
344
345 rootKey.SetValue(key, value);
346
347 rootKey.Close();
348
349 }
350
351 catch (Exception)
352
353 {
354
355 throw;
356
357 }
358
359 }
360
361 /// <summary>
362
363 /// 创建公钥文件
364
365 /// </summary>
366
367 /// <param name="path"></param>
368
369 /// <param name="publickey"></param>
370
371 public void CreatePublicKeyXML(string path, string publickey)
372
373 {
374
375 try
376
377 {
378
379 FileStream publickeyxml = new FileStream(path, FileMode.Create);
380
381 StreamWriter sw = new StreamWriter(publickeyxml);
382
383 sw.WriteLine(publickey);
384
385 sw.Close();
386
387 publickeyxml.Close();
388
389 }
390
391 catch
392
393 {
394
395 throw;
396
397 }
398
399 }
400
401 /// <summary>
402
403 /// 创建私钥文件
404
405 /// </summary>
406
407 /// <param name="path"></param>
408
409 /// <param name="privatekey"></param>
410
411 public void CreatePrivateKeyXML(string path, string privatekey)
412
413 {
414
415 try
416
417 {
418
419 FileStream privatekeyxml = new FileStream(path, FileMode.Create);
420
421 StreamWriter sw = new StreamWriter(privatekeyxml);
422
423 sw.WriteLine(privatekey);
424
425 sw.Close();
426
427 privatekeyxml.Close();
428
429 }
430
431 catch
432
433 {
434
435 throw;
436
437 }
438
439 }
440
441 /// <summary>
442
443 /// 读取公钥
444
445 /// </summary>
446
447 /// <param name="path"></param>
448
449 /// <returns></returns>
450
451 public string ReadPublicKey(string path)
452
453 {
454
455 StreamReader reader = new StreamReader(path);
456
457 string publickey = reader.ReadToEnd();
458
459 reader.Close();
460
461 return publickey;
462
463 }
464
465 /// <summary>
466
467 /// 读取私钥
468
469 /// </summary>
470
471 /// <param name="path"></param>
472
473 /// <returns></returns>
474
475 public string ReadPrivateKey(string path)
476
477 {
478
479 StreamReader reader = new StreamReader(path);
480
481 string privatekey = reader.ReadToEnd();
482
483 reader.Close();
484
485 return privatekey;
486
487 }
488
489 /// <summary>
490
491 /// 初始化注册表,程序运行时调用,在调用之前更新公钥xml
492
493 /// </summary>
494
495 /// <param name="path">公钥路径</param>
496
497 public void InitialReg(string path)
498
499 {
500
501 Registry.LocalMachine.CreateSubKey(@"SOFTWARE\JX\Register");
502
503 Random ra = new Random();
504
505 string publickey = this.ReadPublicKey(path);
506
507 if (Registry.LocalMachine.OpenSubKey(@"SOFTWARE\JX\Register").ValueCount <= 0)
508
509 {
510
511 this.WriteReg("RegisterRandom", ra.Next(1,100000).ToString());
512
513 this.WriteReg("RegisterPublicKey", publickey);
514
515 }
516
517 else
518
519 {
520
521 this.WriteReg("RegisterPublicKey", publickey);
522
523 }
524
525 }
526

如果是要对发送的消息进行加密和解密,加密时用公钥,解密时用私钥,即使密文被窃取也无法破解。

如果是要对软件进行注册,生成注册码,则服务端将用户的硬盘号用私钥加密,客户端用公钥解密,解密后将客户端的硬盘号进行MD5加密,将得到的结果和解密后的结果进行比较,如果相同,说明是注册用户,否则为非注册用户。

 

 

本文来自CSDN博客:http://blog.csdn.net/llwinnner/archive/2009/03/21/4011936.aspx

posted on 2010-02-05 11:03  何时能出头  阅读(1505)  评论(0编辑  收藏  举报