加密、解密字符串时,需要用到加密类和内存流,所以首先需要在命名控件中需要进行引入

 

static string encryptKey = "Oyea"; //定义秘钥
 public string Encrypt(string str)  //加密
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//实例化加密对象
            byte[] key = Encoding.Unicode.GetBytes(encryptKey);//定义字节数组,用来存储秘钥
            byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组,用来要存储加密的字符串
            MemoryStream mStream = new MemoryStream();//实例化内存流对象
            //使用内存流实例化加密对象
            CryptoStream cStream = new CryptoStream(mStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
            cStream.Write(data,0, data.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String( mStream.ToArray());
        }        public string DesCrypr(string str)
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//定义加密类对象
            byte[] key = Encoding.Unicode.GetBytes(encryptKey);
            byte[] data = Convert.FromBase64String(str);
            MemoryStream mStram = new MemoryStream();//实例化内存流对象
            CryptoStream cStream = new CryptoStream(mStram, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
            cStream.Write(data,0,data.Length);
            cStream.FlushFinalBlock();
            return Encoding.Unicode.GetString(mStram.ToArray());        }
//MD5加密  不可逆
 public string GetMd5(string str) //加密方法
        {
            string strResult = string.Empty;
            //创建实例
            MD5 md5 = MD5.Create();
            byte[] strByte=   Encoding.Default.GetBytes(str); //字符转换成字符数组
            byte[] md5Buffer=    md5.ComputeHash(strByte, 0, strByte.Length); //转换加密数组
            for (int i = 0; i < md5Buffer.Length; i++)  //循环
            {
                strResult += md5Buffer[i].ToString("X2"); //自己转换成16进制
            }
            return    strResult;
        }