1 private SymmetricAlgorithm mobjCryptoService;
2 private string Key;
3 ///// <summary>
4 ///// 对称加密类的构造函数
5 ///// </summary>
6 public SymmetricMethod() {
7 mobjCryptoService = new RijndaelManaged();
8 Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
9 }
10 /// <summary>
11 /// 获得密钥
12 /// </summary>
13 /// <returns>密钥</returns>
14 private byte[] GetLegalKey()
15 { string sTemp = Key; mobjCryptoService.GenerateKey();
16 byte[] bytTemp = mobjCryptoService.Key; int KeyLength = bytTemp.Length;
17 if (sTemp.Length > KeyLength) sTemp = sTemp.Substring(0, KeyLength);
18 else if (sTemp.Length < KeyLength) sTemp = sTemp.PadRight(KeyLength, ‘ ‘);
19 return ASCIIEncoding.ASCII.GetBytes(sTemp);
20 }
21 /// <summary>
22 /// 获得初始向量IV
23 /// </summary>
24 /// <returns>初试向量IV</returns>
25 private byte[] GetLegalIV() {
26 string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
27 mobjCryptoService.GenerateIV();
28 byte[] bytTemp = mobjCryptoService.IV;
29 int IVLength = bytTemp.Length;
30 if (sTemp.Length > IVLength)
31 sTemp = sTemp.Substring(0, IVLength);
32 else if (sTemp.Length < IVLength)
33 sTemp = sTemp.PadRight(IVLength, ‘ ‘);
34 return ASCIIEncoding.ASCII.GetBytes(sTemp);
35 }
36
37 /// <summary>
38 /// 加密方法
39 /// </summary>
40 ///<param name="Source">待加密的串</param>
41 /// <returns>经过加密的串</returns>
42 public string Encrypto(string Source) {
43 byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
44 MemoryStream ms = new MemoryStream();
45 mobjCryptoService.Key = GetLegalKey();
46 mobjCryptoService.IV = GetLegalIV();
47 ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
48 CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
49 cs.Write(bytIn, 0, bytIn.Length);
50 cs.FlushFinalBlock();
51 ms.Close();
52 byte[] bytOut = ms.ToArray();
53 return Convert.ToBase64String(bytOut);
54 }
55
56
59 /// <summary>
60 /// 解密方法
61 /// </summary>
62 /// <param name="Source">待解密的串</param>
63 /// <returns>经过解密的串</returns>
64 public string Decrypto(string Source)
65 {
66 byte[] bytIn = Convert.FromBase64String(Source);
67 MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
68 mobjCryptoService.Key = GetLegalKey();
69 mobjCryptoService.IV = GetLegalIV();
70 ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
71 CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
72 StreamReader sr = new StreamReader(cs);
73 return sr.ReadToEnd();
74 }
潜移默化学会WPF(安全篇<二>)--C#对称加密算法 - AYUI框架 - 博客园
原文:https://www.cnblogs.com/lonelyxmas/p/10459121.html