欢迎来到【一个大西瓜】的博客

不曾为梦想奋斗,拿什么去燃烧青春。有梦之人亦终将老去,但少年心气如昨。
太阳每一个时刻都同时是夕阳和朝阳,每天她沉入西边,意味着她同时从另一面土地升起。
扩大
缩小

【工具类】

加解密

public class EncryptUtils
{
    #region Base64加密解密
    /// <summary>
    /// Base64加密
    /// </summary>
    /// <param name="input">需要加密的字符串</param>
    /// <returns></returns>
    public static string Base64Encrypt(string input)
    {
        return Base64Encrypt(input, new UTF8Encoding());
    }

    /// <summary>
    /// Base64加密
    /// </summary>
    /// <param name="input">需要加密的字符串</param>
    /// <param name="encode">字符编码</param>
    /// <returns></returns>
    public static string Base64Encrypt(string input, Encoding encode)
    {
        return Convert.ToBase64String(encode.GetBytes(input));
    }

    /// <summary>
    /// Base64解密
    /// </summary>
    /// <param name="input">需要解密的字符串</param>
    /// <returns></returns>
    public static string Base64Decrypt(string input)
    {
        return Base64Decrypt(input, new UTF8Encoding());
    }

    /// <summary>
    /// Base64解密
    /// </summary>
    /// <param name="input">需要解密的字符串</param>
    /// <param name="encode">字符的编码</param>
    /// <returns></returns>
    public static string Base64Decrypt(string input, Encoding encode)
    {
        return encode.GetString(Convert.FromBase64String(input));
    }
    #endregion

    #region DES加密解密
    /// <summary>
    /// DES加密
    /// </summary>
    /// <param name="data">加密数据</param>
    /// <param name="key">8位字符的密钥字符串</param>
    /// <param name="iv">8位字符的初始化向量字符串</param>
    /// <returns></returns>
    public static string DESEncrypt(string data, string key, string iv)
    {
        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        int i = cryptoProvider.KeySize;
        MemoryStream ms = new MemoryStream();
        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

        StreamWriter sw = new StreamWriter(cst);
        sw.Write(data);
        sw.Flush();
        cst.FlushFinalBlock();
        sw.Flush();
        return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
    }

    /// <summary>
    /// DES解密
    /// </summary>
    /// <param name="data">解密数据</param>
    /// <param name="key">8位字符的密钥字符串(需要和加密时相同)</param>
    /// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
    /// <returns></returns>
    public static string DESDecrypt(string data, string key, string iv)
    {
        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);

        byte[] byEnc;
        try
        {
            byEnc = Convert.FromBase64String(data);
        }
        catch
        {
            return null;
        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream ms = new MemoryStream(byEnc);
        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
        StreamReader sr = new StreamReader(cst);
        return sr.ReadToEnd();
    }
    #endregion

    #region MD5加密
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="input">需要加密的字符串</param>
    /// <returns></returns>
    public static string MD5Encrypt(string input)
    {
        return MD5Encrypt(input, new UTF8Encoding());
    }

    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="input">需要加密的字符串</param>
    /// <param name="encode">字符的编码</param>
    /// <returns></returns>
    public static string MD5Encrypt(string input, Encoding encode)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] t = md5.ComputeHash(encode.GetBytes(input));
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < t.Length; i++)
            sb.Append(t[i].ToString("x").PadLeft(2, '0'));
        return sb.ToString();
    }

    /// <summary>
    /// MD5对文件流加密
    /// </summary>
    /// <param name="sr"></param>
    /// <returns></returns>
    public static string MD5Encrypt(Stream stream)
    {
        MD5 md5serv = MD5CryptoServiceProvider.Create();
        byte[] buffer = md5serv.ComputeHash(stream);
        StringBuilder sb = new StringBuilder();
        foreach (byte var in buffer)
            sb.Append(var.ToString("x2"));
        return sb.ToString();
    }

    /// <summary>
    /// MD5加密(返回16位加密串)
    /// </summary>
    /// <param name="input"></param>
    /// <param name="encode"></param>
    /// <returns></returns>
    public static string MD5Encrypt16(string input, Encoding encode)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        string result = BitConverter.ToString(md5.ComputeHash(encode.GetBytes(input)), 4, 8);
        result = result.Replace("-", "");
        return result;
    }
    #endregion

    #region 3DES 加密解密

    public static string DES3Encrypt(string data, string key)
    {
        TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

        DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
        DES.Mode = CipherMode.CBC;
        DES.Padding = PaddingMode.PKCS7;

        ICryptoTransform DESEncrypt = DES.CreateEncryptor();

        byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(data);
        return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
    }

    public static string DES3Decrypt(string data, string key)
    {
        TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

        DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
        DES.Mode = CipherMode.CBC;
        DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

        ICryptoTransform DESDecrypt = DES.CreateDecryptor();

        string result = "";
        try
        {
            byte[] Buffer = Convert.FromBase64String(data);
            result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }
        catch (Exception e)
        {

        }
        return result;
    }

    #endregion

    #region HASH-1加密
    /// <summary>
    /// use sha1 to encrypt string
    /// </summary>
    public string SHA1_Encrypt(string Source_String)
    {
        byte[] StrRes = Encoding.Default.GetBytes(Source_String);
        HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
        StrRes = iSHA.ComputeHash(StrRes);
        StringBuilder EnText = new StringBuilder();
        foreach (byte iByte in StrRes)
        {
            EnText.AppendFormat("{0:x2}", iByte);
        }
        return EnText.ToString();
    }
    #endregion
}
View Code

http通信

public class HttpUtilts
{
            #region http请求
    /// <summary>
    /// 默认UserAgent
    /// </summary>
    private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    /// <summary>
    /// 默认Timeout:10000毫秒(10秒)
    /// </summary>
    private static readonly int DefaultTimeout = 10000;
    /// <summary>
    /// 默认contentType
    /// </summary>
    private static readonly string DefaultcontentType = "application/x-www-form-urlencoded";

    /// <summary>
    /// http请求
    /// </summary>
    /// <param name="url">请求地址(必须)</param>
    /// <param name="content">请求内容</param>
    /// <param name="method">请求方式(必须)</param>
    /// <param name="headers">需要添加的标头信息</param>
    /// <param name="encoding">字符编码(默认:UTF8)</param>
    /// <param name="contentType">字符格式(默认:application/x-www-form-urlencoded)</param>
    /// <param name="userName">用户名</param>
    /// <param name="password">密码(与用户名同时存在)</param>
    /// <param name="timeout">超时时间默认(10秒)</param>
    /// <returns>响应返回值</returns>
    public static string CreateHttpResponse(string url, string content, string method, Dictionary<string, string> headers, Encoding encoding, string contentType, string userName, string password, ref bool IsAbnormal, int timeout = 0)
    {
        //记录日志
        encoding = encoding == null ? Encoding.UTF8 : encoding;
        if (string.IsNullOrEmpty(url)) { return "URL错误!"; }
        if (string.IsNullOrEmpty(method)) { return "method错误!"; }

        string responseData = String.Empty;
        try
        {
            //实例化请求
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            //请求类型
            request.Method = method;

            request.KeepAlive = false;

            request.AllowAutoRedirect = true;

            //标头
            if (headers != null) for (var i = 0; i < headers.Count; i++) { var item = headers.ElementAt(i); request.Headers.Add(item.Key, item.Value); }

            //超时时间()
            request.Timeout = timeout == 0 ? DefaultTimeout : timeout;

            //类型
            request.ContentType = string.IsNullOrEmpty(contentType) ? DefaultcontentType : contentType;

            //请求参数
            if (!string.IsNullOrEmpty(content))
            {
                byte[] Data = encoding.GetBytes(content);
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(Data, 0, Data.Length);
                    reqStream.Close();
                }
                //请求参数长度
                if (request.ContentLength != Data.Length) request.ContentLength = Data.Length;
            }
            else
            {
                request.ContentLength = 0;
            }

            //向路由提交基本身份验证
            if (!string.IsNullOrEmpty(userName) || !string.IsNullOrEmpty(password))
            {
                string code = Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", userName, password)));
                request.Headers.Add("Authorization", "Basic " + code);
            }

            //发起请求,返回响应内容
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    IsAbnormal = true;
                    responseData = reader.ReadToEnd().ToString();
                }
            }
        }
        catch (WebException ex)
        {
            IsAbnormal = false;
            //记录日志
            //CustomMethod.LogErrorLog("Url:" + url, "CustomData_CreateHttpResponse");
            //CustomMethod.LogErrorLog(ex.ToString(), "CustomData_CreateHttpResponse");
            //返回的响应
            HttpWebResponse response = (HttpWebResponse)ex.Response;
            //如果是错误400或者404则返回错误信息
            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    using (Stream _Stream = response.GetResponseStream())
                    {
                        using (StreamReader _Reader = new StreamReader(_Stream))
                        {
                            string _JsonData = _Reader.ReadToEnd();

                            //记录日志
                            //CustomMethod.LogErrorLog(_JsonData, "CustomData_CreateHttpResponse");

                            ExceptionModel Em = JsonConvert.DeserializeObject<ExceptionModel>(_JsonData);

                            return Em.error_description;
                        }
                    }
                }
            }
            return "服务器异常,请联系管理员!";

        }
        return responseData;
    }
    public class ExceptionModel
    {
        public string error { get; set; }
        public string error_description { get; set; }
    }
    #endregion
}
View Code

 

posted on 2018-01-29 15:30  一个大西瓜咚咚咚  阅读(404)  评论(0编辑  收藏  举报

导航