C# post带加密参数下载数据到zip文件

下面是下载和保存的全部代码:

        private bool _GetSqlDataFromServer(String strFileName)
        {
            bool tempFlag = false;
            // 获取本地版本是否存在
            String tempVersions = _GetCurVersions();
            if (null == tempVersions && "" == tempVersions)
            {
                tempVersions = "0";
            }


            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("guid", "{0000-HUANG-0000}");
            parameters.Add("menu_item", tempVersions);

            try 
            {
                FileStream FStream;
                if (File.Exists(strFileName))
                {
                    //打开要下载的文件
                    FStream = File.OpenWrite(strFileName);
                }
                else
                {
                    //文件不保存创建一个文件
                    FStream = new FileStream(strFileName, FileMode.Create);
                }
                Stream myStream = HttpHelper.CreatePostHttpResponse(@"http://192.168.1.209:83/api2/pos_sync/", parameters, Encoding.UTF8).GetResponseStream();
                //定义一个字节数据
                byte[] btContent = new byte[512];
                int intSize = 0;
                intSize = myStream.Read(btContent, 0, 512);
                while (intSize > 0)
                {
                    FStream.Write(btContent, 0, intSize);
                    intSize = myStream.Read(btContent, 0, 512);
                }

                //关闭流
                FStream.Close();
                myStream.Close();
                tempFlag = true;
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message, Properties.Resources.login_note);
            }
            return tempFlag;
        }

 

第一步post请求的函数:

        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset)
        {
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = DefaultUserAgent;
            //如果需要POST数据     
            if (!(parameters == null || parameters.Count == 0))
            { 
                string json = (new JavaScriptSerializer()).Serialize(parameters);
                byte []data = AESHelper.AESEncryptEx(json, "COOLROIDagilePOS", "0000000000000000");
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

先将请求的参数保存到字典,然后转成json,在进行AES加密

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("guid", "{0000-HUANG-0000}");
            parameters.Add("menu_item", tempVersions);
                // 将参数字典转换成json字符串
                string json = (new JavaScriptSerializer()).Serialize(parameters);
                // 将json字符串加密成byte数组
                byte []data = AESHelper.AESEncryptEx(json, "COOLROIDagilePOS", "0000000000000000");

注意:转json需要引入using System.Web.Script.Serialization;同时需要引用System.Web.Extensions框架

下面是AES加密算法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO; 

namespace AgileManager
{
    class AESHelper
    {
        /// <summary>
        /// 有密码的AES加密 
        /// </summary>
        /// <param name="text">加密字符</param>
        /// <param name="password">加密的密码</param>
        /// <param name="iv">密钥</param>
        /// <returns></returns>
        public static string AESEncrypt(string text, string password, string iv)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.Zeros;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;


            byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
            rijndaelCipher.IV = ivBytes;

            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

            byte[] plainText = Encoding.UTF8.GetBytes(text);

            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            return Convert.ToBase64String(cipherBytes);

        }

        public static byte[] AESEncryptEx(string text, string password, string iv)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.Zeros;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;


            byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
            rijndaelCipher.IV = ivBytes;

            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

            byte[] plainText = Encoding.UTF8.GetBytes(text);

            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            return cipherBytes;

        }

        /// <summary>
        /// 随机生成密钥
        /// </summary>
        /// <returns></returns>
        public static string GetIv(int n)
        {
            char[] arrChar = new char[]{
           'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
           '0','1','2','3','4','5','6','7','8','9',
           'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
          };

            StringBuilder num = new StringBuilder();

            Random rnd = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < n; i++)
            {
                num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());

            }

            return num.ToString();
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string AESDecrypt(string text, string password, string iv)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] encryptedData = Convert.FromBase64String(text);

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
            rijndaelCipher.IV = ivBytes;

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            return Encoding.UTF8.GetString(plainText);

        }
    }
}

第二步,将下载的返回的数据流保存到strFileName的zip文件中,先判断文件是否存在,不存在新建一个文件,存在先删除。

                FileStream FStream;
                if (File.Exists(strFileName))
                {
                    //打开要下载的文件
                    FStream = File.OpenWrite(strFileName);
                }
                else
                {
                    //文件不保存创建一个文件
                    FStream = new FileStream(strFileName, FileMode.Create);
                }
                Stream myStream = HttpHelper.CreatePostHttpResponse(@"http://192.168.1.209:83/api2/pos_sync/", parameters, Encoding.UTF8).GetResponseStream();
                //定义一个字节数据
                byte[] btContent = new byte[512];
                int intSize = 0;
                intSize = myStream.Read(btContent, 0, 512);
                while (intSize > 0)
                {
                    FStream.Write(btContent, 0, intSize);
                    intSize = myStream.Read(btContent, 0, 512);
                }

                //关闭流
                FStream.Close();
                myStream.Close();
                tempFlag = true;

第三步,将文件解压

            bool tempFlag = _GetSqlDataFromServer("sql_data_file.zip");
            if (true == tempFlag)
            {
                // 解压数据库数据文件
                tempFlag = ZipArchive.UnZip2("sql_data_file.zip", "sql_data");
                // 解压成功才导入数据
                if (true == tempFlag)
                {
                    // 将数据库文件的数据导入本地数据
                    string[] tempName = Directory.GetFiles(@"sql_data");
                    int i = 0;
                    System.Collections.ArrayList tempList;
                    string tempVersion;
                    foreach (var item in tempName)
                    {
                        var temp = System.IO.Path.GetFileName(item);
                        if ("versions" == temp)
                        {
                            tempList = _GetFileContext(tempName[i]);
                            tempVersion = tempList[0].ToString().Substring(10);
                            _SaveCurVersions(tempVersion);
                        }
                        else
                        {
                            _LoadSqlDataInFile(@"sql_data", temp);
                        }
                        ++i;
                    }
                    MessageBox.Show(Properties.Resources.str_load_succeed_tips, Properties.Resources.login_note);
                }
                else
                {
                    MessageBox.Show(Properties.Resources.str_version_last_tips, Properties.Resources.login_note);
                }
            }

 

转载于:https://my.oschina.net/LongSF/blog/715785

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值