服务器之家

服务器之家 > 正文

.NET使用RSA加密解密的方法

时间:2020-06-10 14:15     来源/作者:风灵使

本文实例为大家分享了.NET使用RSA加密解密的具体代码,供大家参考,具体内容如下

PassWordHelper.cs代码:

 

?
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
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
 
namespace Utils
{
  /// <summary>
  /// 密码加密解密操作相关类
  /// </summary>
  public static class PassWordHelper
  {
    #region MD5 加密
 
    /// <summary>
    /// MD5加密
    /// </summary>
    public static string Md532(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      MD5 md5 = MD5.Create();
      return HashAlgorithmBase(md5, source, encoding);
    }
 
    /// <summary>
    /// 加盐MD5加密
    /// </summary>
    public static string Md532Salt(this string source, string salt)
    {
      return string.IsNullOrEmpty(source) ? source.Md532() : (source + "『" + salt + "』").Md532();
    }
 
    #endregion
 
    #region SHA 加密
 
    /// <summary>
    /// SHA1 加密
    /// </summary>
    public static string Sha1(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      SHA1 sha1 = new SHA1CryptoServiceProvider();
      return HashAlgorithmBase(sha1, source, encoding);
    }
 
    /// <summary>
    /// SHA256 加密
    /// </summary>
    public static string Sha256(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      SHA256 sha256 = new SHA256Managed();
      return HashAlgorithmBase(sha256, source, encoding);
    }
 
    /// <summary>
    /// SHA512 加密
    /// </summary>
    public static string Sha512(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      SHA512 sha512 = new SHA512Managed();
      return HashAlgorithmBase(sha512, source, encoding);
    }
 
    #endregion
 
    #region HMAC 加密
 
    /// <summary>
    /// HmacSha1 加密
    /// </summary>
    public static string HmacSha1(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA1 hmacSha1 = new HMACSHA1(keyStr);
      return HashAlgorithmBase(hmacSha1, source, encoding);
    }
 
    /// <summary>
    /// HmacSha256 加密
    /// </summary>
    public static string HmacSha256(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA256 hmacSha256 = new HMACSHA256(keyStr);
      return HashAlgorithmBase(hmacSha256, source, encoding);
    }
 
    /// <summary>
    /// HmacSha384 加密
    /// </summary>
    public static string HmacSha384(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA384 hmacSha384 = new HMACSHA384(keyStr);
      return HashAlgorithmBase(hmacSha384, source, encoding);
    }
 
    /// <summary>
    /// HmacSha512 加密
    /// </summary>
    public static string HmacSha512(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA512 hmacSha512 = new HMACSHA512(keyStr);
      return HashAlgorithmBase(hmacSha512, source, encoding);
    }
 
    /// <summary>
    /// HmacMd5 加密
    /// </summary>
    public static string HmacMd5(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACMD5 hmacMd5 = new HMACMD5(keyStr);
      return HashAlgorithmBase(hmacMd5, source, encoding);
    }
 
    /// <summary>
    /// HmacRipeMd160 加密
    /// </summary>
    public static string HmacRipeMd160(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACRIPEMD160 hmacRipeMd160 = new HMACRIPEMD160(keyStr);
      return HashAlgorithmBase(hmacRipeMd160, source, encoding);
    }
 
    #endregion
 
    #region AES 加密解密
 
    /// <summary>
    /// AES加密
    /// </summary>
    /// <param name="source">待加密字段</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static string AesStr(this string source, string keyVal, string ivVal)
    {
      var encoding = Encoding.UTF8;
      byte[] btKey = keyVal.FormatByte(encoding);
      byte[] btIv = ivVal.FormatByte(encoding);
      byte[] byteArray = encoding.GetBytes(source);
      string encrypt;
      Rijndael aes = Rijndael.Create();
      using (MemoryStream mStream = new MemoryStream())
      {
        using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write))
        {
          cStream.Write(byteArray, 0, byteArray.Length);
          cStream.FlushFinalBlock();
          encrypt = Convert.ToBase64String(mStream.ToArray());
        }
      }
      aes.Clear();
      return encrypt;
    }
 
    /// <summary>
    /// AES解密
    /// </summary>
    /// <param name="source">待加密字段</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static string UnAesStr(this string source, string keyVal, string ivVal)
    {
      var encoding = Encoding.UTF8;
      byte[] btKey = keyVal.FormatByte(encoding);
      byte[] btIv = ivVal.FormatByte(encoding);
      byte[] byteArray = Convert.FromBase64String(source);
      string decrypt;
      Rijndael aes = Rijndael.Create();
      using (MemoryStream mStream = new MemoryStream())
      {
        using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write))
        {
          cStream.Write(byteArray, 0, byteArray.Length);
          cStream.FlushFinalBlock();
          decrypt = encoding.GetString(mStream.ToArray());
        }
      }
      aes.Clear();
      return decrypt;
    }
 
    /// <summary>
    /// AES Byte类型 加密
    /// </summary>
    /// <param name="data">待加密明文</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static byte[] AesByte(this byte[] data, string keyVal, string ivVal)
    {
      byte[] bKey = new byte[32];
      Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
      byte[] bVector = new byte[16];
      Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
      byte[] cryptograph;
      Rijndael aes = Rijndael.Create();
      try
      {
        using (MemoryStream mStream = new MemoryStream())
        {
          using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write))
          {
            cStream.Write(data, 0, data.Length);
            cStream.FlushFinalBlock();
            cryptograph = mStream.ToArray();
          }
        }
      }
      catch
      {
        cryptograph = null;
      }
      return cryptograph;
    }
 
    /// <summary>
    /// AES Byte类型 解密
    /// </summary>
    /// <param name="data">待解密明文</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static byte[] UnAesByte(this byte[] data, string keyVal, string ivVal)
    {
      byte[] bKey = new byte[32];
      Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
      byte[] bVector = new byte[16];
      Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
      byte[] original;
      Rijndael aes = Rijndael.Create();
      try
      {
        using (MemoryStream mStream = new MemoryStream(data))
        {
          using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read))
          {
            using (MemoryStream originalMemory = new MemoryStream())
            {
              byte[] buffer = new byte[1024];
              int readBytes;
              while ((readBytes = cStream.Read(buffer, 0, buffer.Length)) > 0)
              {
                originalMemory.Write(buffer, 0, readBytes);
              }
 
              original = originalMemory.ToArray();
            }
          }
        }
      }
      catch
      {
        original = null;
      }
      return original;
    }
 
    #endregion
 
    #region RSA 加密解密
 
    //密钥对,请配合密钥生成工具使用『 http://download.csdn.net/detail/downiis6/9464639 』
    private const string PublicRsaKey = @"<RSAKeyValue>
 <Modulus>8Yvf/LjXRhCuOREk2CuSYvbD/RadwJ4sjHREIpQVKwkTlG3BtRgpnaMcoeLAesmwvpBWnqK4hBkYLxhRj+NEKnlGrJ+LkNMnZr0/4CMuulZFAnx7iQYaSq7Eh7kBKGLofc05CjZguYpnPNxHIv4VNx+a9tIh+hnhjrmkJLUm3l0=</Modulus>
 <Exponent>AQAB</Exponent>
</RSAKeyValue>";
    private const string PrivateRsaKey = @"<RSAKeyValue>
 <Modulus>8Yvf/LjXRhCuOREk2CuSYvbD/RadwJ4sjHREIpQVKwkTlG3BtRgpnaMcoeLAesmwvpBWnqK4hBkYLxhRj+NEKnlGrJ+LkNMnZr0/4CMuulZFAnx7iQYaSq7Eh7kBKGLofc05CjZguYpnPNxHIv4VNx+a9tIh+hnhjrmkJLUm3l0=</Modulus>
 <Exponent>AQAB</Exponent>
 <P>/xAaa/4dtDxcEAk5koSZBPjuxqvKJikpwLA1nCm3xxAUMDVxSwQyr+SHFaCnBN9kqaNkQCY6kDCfJXFWPOj0Bw==</P>
 <Q>8m8PFVA4sO0oEKMVQxt+ivDTHFuk/W154UL3IgC9Y6bzlvYewXZSzZHmxZXXM1lFtwoYG/k+focXBITsiJepew==</Q>
 <DP>ONVSvdt6rO2CKgSUMoSfQA9jzRr8STKE3i2lVG2rSIzZosBVxTxjOvQ18WjBroFEgdQpg23BQN3EqGgvqhTSQw==</DP>
 <DQ>gfp7SsEM9AbioTDemHEoQlPly+FyrxE/9D8UAt4ErGX5WamxSaYntOGRqcOxcm1djEpULMNP90R0Wc7uhjlR+w==</DQ>
 <InverseQ>C0eBsp2iMOxWwKo+EzkHOP0H+YOitUVgjekGXmSt9a3TvikQNaJ5ATlqKsZaMGsnB6UIHei+kUaCusVX0HgQ2A==</InverseQ>
 <D>tPYxEfo9Nb3LeO+SJe3G1yO+w37NIwCdqYB1h15f2YUMSThNVmpKy1HnYpUp1RQDuVETw/duu3C9gJL8kAsZBjBrVZ0zC/JZsgvSNprfUK3Asc4FgFsGfQGKW1nvvgdMbvqr4ClB0R8czkki+f9Oc5ea/RMqXxlI+XjzMYDEknU=</D>
</RSAKeyValue>";
 
    /// <summary>
    /// RSA 加密
    /// </summary>
    public static string Rsa(this string source)
    {
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      rsa.FromXmlString(PublicRsaKey);
      var cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(source), true);
      return Convert.ToBase64String(cipherbytes);
    }
 
    /// <summary>
    /// RSA解密
    /// </summary>
    public static string UnRsa(this string source)
    {
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      rsa.FromXmlString(PrivateRsaKey);
      var cipherbytes = rsa.Decrypt(Convert.FromBase64String(source), true);
      return Encoding.UTF8.GetString(cipherbytes);
    }
 
    #endregion
 
    #region DES 加密解密
 
    /// <summary>
    /// DES 加密
    /// </summary>
    public static string Des(this string source, string keyVal, string ivVal)
    {
      try
      {
        byte[] data = Encoding.UTF8.GetBytes(source);
        var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
        var desencrypt = des.CreateEncryptor();
        byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
        return BitConverter.ToString(result);
      }
      catch { return "转换出错!"; }
    }
 
    /// <summary>
    /// DES 解密
    /// </summary>
    public static string UnDes(this string source, string keyVal, string ivVal)
    {
      try
      {
        string[] sInput = source.Split("-".ToCharArray());
        byte[] data = new byte[sInput.Length];
        for (int i = 0; i < sInput.Length; i++)
        {
          data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
        }
        var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
        var desencrypt = des.CreateDecryptor();
        byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
        return Encoding.UTF8.GetString(result);
      }
      catch { return "解密出错!"; }
    }
 
    #endregion
 
    #region TripleDES 加密解密
 
    /// <summary>
    /// DES3 加密
    /// </summary>
    public static string Des3(this string source, string keyVal)
    {
      try
      {
        TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
        {
          Key = keyVal.FormatByte(Encoding.UTF8),
          Mode = CipherMode.ECB,
          Padding = PaddingMode.PKCS7
        };
        using (MemoryStream ms = new MemoryStream())
        {
          byte[] btArray = Encoding.UTF8.GetBytes(source);
          try
          {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
              cs.Write(btArray, 0, btArray.Length);
              cs.FlushFinalBlock();
            }
            return ms.ToArray().Bytes2Str();
          }
          catch { return source; }
        }
      }
      catch
      {
        return "TripleDES加密出现错误";
      }
    }
 
    /// <summary>
    /// DES3 解密
    /// </summary>
    public static string UnDes3(this string source, string keyVal)
    {
      try
      {
        byte[] byArray = source.Str2Bytes();
        TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
        {
          Key = keyVal.FormatByte(Encoding.UTF8),
          Mode = CipherMode.ECB,
          Padding = PaddingMode.PKCS7
        };
        using (MemoryStream ms = new MemoryStream())
        {
          using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
          {
            cs.Write(byArray, 0, byArray.Length);
            cs.FlushFinalBlock();
            cs.Close();
            ms.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
          }
        }
      }
      catch
      {
        return "TripleDES解密出现错误";
      }
    }
 
    #endregion
 
    #region BASE64 加密解密
 
    /// <summary>
    /// BASE64 加密
    /// </summary>
    /// <param name="source">待加密字段</param>
    /// <returns></returns>
    public static string Base64(this string source)
    {
      var btArray = Encoding.UTF8.GetBytes(source);
      return Convert.ToBase64String(btArray, 0, btArray.Length);
    }
 
    /// <summary>
    /// BASE64 解密
    /// </summary>
    /// <param name="source">待解密字段</param>
    /// <returns></returns>
    public static string UnBase64(this string source)
    {
      var btArray = Convert.FromBase64String(source);
      return Encoding.UTF8.GetString(btArray);
    }
 
    #endregion
 
    #region 内部方法
 
    /// <summary>
    /// 转成数组
    /// </summary>
    private static byte[] Str2Bytes(this string source)
    {
      source = source.Replace(" ", "");
      byte[] buffer = new byte[source.Length / 2];
      for (int i = 0; i < source.Length; i += 2) buffer[i / 2] = Convert.ToByte(source.Substring(i, 2), 16);
      return buffer;
    }
 
    /// <summary>
    /// 转换成字符串
    /// </summary>
    private static string Bytes2Str(this IEnumerable<byte> source, string formatStr = "{0:X2}")
    {
      StringBuilder pwd = new StringBuilder();
      foreach (byte btStr in source) { pwd.AppendFormat(formatStr, btStr); }
      return pwd.ToString();
    }
 
    private static byte[] FormatByte(this string strVal, Encoding encoding)
    {
      return encoding.GetBytes(strVal.Base64().Substring(0, 16).ToUpper());
    }
 
    /// <summary>
    /// HashAlgorithm 加密统一方法
    /// </summary>
    private static string HashAlgorithmBase(HashAlgorithm hashAlgorithmObj, string source, Encoding encoding)
    {
      byte[] btStr = encoding.GetBytes(source);
      byte[] hashStr = hashAlgorithmObj.ComputeHash(btStr);
      return hashStr.Bytes2Str();
    }
 
    #endregion
  }
}

Program.cs代码:

 

?
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
 
      string plainText = "这是一条被和谐的消息!";
      //加密明文,获得密文
      string EncryptText= Utils.PassWordHelper.Rsa(plainText);
      Console.WriteLine(EncryptText);
 
      //解密密文,获得明文
      string DecryptText = Utils.PassWordHelper.UnRsa(EncryptText);
      Console.WriteLine(DecryptText);
      Console.ReadKey();
 
    }
  }
}

运行结果如图:

.NET使用RSA加密解密的方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/WuLex/article/details/53856785

标签:

相关文章

热门资讯

歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
返回顶部