简单的加密与解密代码

 1 using  System;
 2 using  System.IO;
 3 using  System.Security.Cryptography;
 4 using  System.Text;
 5
 6 namespace  FaibClass.Encrypting
 7 {
 8
 9    public class BaseEncrypt
10    {
11        ///<summary> 
12        /// 加密
13        /// </summary> 
14        /// <param name="s">需加密的字串</param> 
15        /// <param name="k">密钥</param> 
16        /// <returns></returns> 

17        public static string EncryptString(string s,string k)
18        {
19            byte[] byKey=null;
20            byte[] IV= {0x120x340x560x780x900xAB0xCD0xEF};
21            try
22            {
23                if(k.Length>8)
24                    byKey = System.Text.Encoding.UTF8.GetBytes(k.Substring(0,8));
25                else
26                    byKey = System.Text.Encoding.UTF8.GetBytes((k+(new string('V',8-k.Length))));
27                
28                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
29                byte[] inputByteArray = Encoding.UTF8.GetBytes(s);
30                MemoryStream ms = new MemoryStream();
31                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write) ;
32                cs.Write(inputByteArray, 0, inputByteArray.Length);
33                cs.FlushFinalBlock();
34                return Convert.ToBase64String(ms.ToArray());
35            }

36            catch(System.Exception error)
37            {
38                throw new Exception(error.Message);
39            }

40        }

41
42        ///<summary> 
43        /// 解密
44        /// </summary> 
45        /// <param name="s">需解密的字串</param> 
46        /// <param name="k">密钥</param> 
47        /// <returns></returns> 

48        public static string DecryptString(string s,string k)
49        {
50            byte[] byKey = null;
51            byte[] IV= {0x120x340x560x780x900xAB0xCD0xEF}
52            byte[] inputByteArray = new Byte[s.Length];
53            try
54            {
55                if(k.Length>8)
56                    byKey = System.Text.Encoding.UTF8.GetBytes(k.Substring(0,8));
57                else
58                    byKey = System.Text.Encoding.UTF8.GetBytes((k+(new string('V',8-k.Length))));
59
60                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
61                inputByteArray = Convert.FromBase64String(s);
62                MemoryStream ms = new MemoryStream();
63                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
64                cs.Write(inputByteArray, 0, inputByteArray.Length);
65                cs.FlushFinalBlock();
66                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
67                return encoding.GetString(ms.ToArray());
68            }

69            catch(System.Exception error)
70            {
71                throw new Exception(error.Message);
72            }

73        }

74    }

75}

你可能感兴趣的:(加密)