//验证签名算法 参数字符串+secret+时间戳 MD5加密 /// <summary> /// /// </summary> /// <param name="appId"></param> /// <param name="sign"></param> /// <param name="timeStamp"></param> /// <param name="pInput"></param> /// <returns></returns> // public static bool CheckSign(string key,string pInput) // { // bool result = false; // try // { // //在请求正文添加timespan(时间戳),nonce(随机数),sign(签名参数) // //"{'appId':'1','phone':'13969800321','pwd':'123456','timespan':'201802932828','nonce':'288','sign':'noce288phone13969800321pwd123456timespan201802932828'}" sign用MD5加密 // //入参形式应该为 // //{'Phone':'13969800321','Pwd':'123456',TimeStamp':'20180419029388','DesCode':'abc','Sign':'Phone13969800321Pwd123456TimeStamp20180419029388'} // //sign MD5加密 DesCode为RSA公钥加密 // //入参先用DES解密 // RSACryption rsaInput = new RSACryption(); // DESEncrypt.Key = rsaInput.RSADecrypt(privateKey, key);//运用私钥解密传来的公钥加密过的DES秘钥 // string inputStr = DESEncrypt.DesDecrypt(pInput); // //将入参转为JSON对象 // JObject jobj = JObject.Parse(inputStr); // //然后遍历Json对象所有Key Value // string strParam = ""; // List<string> listParam = new List<string>(); // string sign = ""; // foreach (var j in jobj) // { // if (j.Key == "sign") // { // sign = j.Value.ToString(); // continue; // } // string strKeyValue = j.Key + j.Value; // listParam.Add(strKeyValue); // } // listParam.OrderBy(item => item); // foreach(string str in listParam) // { // strParam += str; // } // //完成排序组合,然后MD5加密 // //然后MD5加密 // string md5ParamStr = MD5Encrypt32(strParam); // if(sign.Trim()==md5ParamStr.Trim()) // { // result = true; // } // else // { // result = false; // } // } // catch(Exception ex) // { // result = false; // } // return result; // } // //PEM格式密钥转XML // /// <summary> // /// RSA私钥格式转换,java->.net // /// </summary> // /// <param name="privateKey">java生成的RSA私钥</param> // /// <returns></returns> // public static string RSAPrivateKeyJava2DotNet(this string privateKey) // { // RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)); // return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>", // Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), // Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())); // } // public static string RSAPublicKeyJava2DotNet(this string publicKey) // { // RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey)); // return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>", // Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()), // Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned())); // } // /// <summary> // /// // /// </summary> // /// <param name="parames"></param> // /// <returns></returns> // public static Tuple<string,string> GetQueryString(Dictionary<string,string> parames) // { // StringBuilder query = new StringBuilder("");//签名字符串 // StringBuilder queryStr = new StringBuilder("");//url参数 // try // { // //将字典按Key首字母排序 // IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parames); // IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator(); // //将所有签名字符串按照KeyValue形式串起来 // if (parames == null || parames.Count < 1) // { // return new Tuple<string, string>("",""); // } // while (dem.MoveNext()) // { // string key = dem.Current.Key; // string value = dem.Current.Value; // if (string.IsNullOrEmpty(key)&&key!="sign") // { // query.Append(key).Append(value); // queryStr.Append("&").Append(key).Append("=").Append(value); // } // } // } // catch (Exception) // { // return new Tuple<string, string>("", ""); // } // return new Tuple<string, string>(query.ToString(), queryStr.ToString().Substring(1, queryStr.Length - 1)); // } #region Post方式提交请求 /// <summary> /// Post方式提交请求 /// </summary> /// <param name="Url">地址</param> /// <param name="postDataStr">form中的参数字符串</param> /// <returns></returns> public static string CreatePostHttpResponse(string url, string postStr, int tradeChannel) { try { StaticInfo.Log("url:" + url.ToString()); StaticInfo.Log("postData:" + postStr.ToString()); // 编辑并Encoding提交的数据 byte[] data = new UTF8Encoding().GetBytes(postStr); //Encoding.UTF8.GetBytes(postStr);// new UTF8Encoding().GetBytes(postDataStr);// // 发送请求 System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.Timeout = 5000; if (tradeChannel == 2) { request.ContentType = "application/json;charset=utf-8"; } else { request.ContentType = "application/xml;charset=utf-8"; } request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } // 获得回复 var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); StaticInfo.Log("responseData:" + responseString.ToString()); return(responseString); } catch (Exception ex) { Console.WriteLine(ex.ToString()); StaticInfo.Log("httppost请求发生异常:" + ex.ToString()); return(""); } }
/// <summary> /// 创建一个Token /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> public static ReturnClass CreatToken(string jsonStr) { ReturnClass rc = new ReturnClass(); try { JObject jObj = new JObject(); jObj = JObject.Parse(jsonStr); if (string.IsNullOrEmpty(jObj["UserName"].ToString()) || string.IsNullOrEmpty(jObj["Password"].ToString())) { rc.Msg = "参数为空"; rc.Code = Code.ERR_Sign; rc.Data = ""; return(rc); } string userName = jObj["UserName"].ToString(); //用户名 string password = StaticInfo.MD5Encrypt32(jObj["Password"].ToString()); //密码 //去数据库查询是否有合法 MySqlParameter[] sp = new MySqlParameter[2]; sp[0] = new MySqlParameter("@account", userName); sp[1] = new MySqlParameter("@password", password); var sqlselect1 = string.Format("select * from ws_system_admin where account=@account and pwd=@password"); //DataRow result=MySqlHelper.GetDataSet(MySqlHelper.Conn,CommandType.Text,sqlselect1,sp).Tables[0].Rows[0]; //DataTable dtneed=MySqlHelper.GetDataSet(MySqlHelper.Conn,CommandType.Text,sqlselect1,sp).Tables[0]; DataTable dataTable = MySqlHelper.GetDataSet(MySqlHelper.Conn, CommandType.Text, sqlselect1, sp).Tables[0]; if (dataTable.Rows.Count < 1) { rc.Msg = "用户名或密码错误"; rc.Code = Code.ERR_Sign; rc.Data = ""; return(rc); } DataRow result = dataTable.Rows[0]; //MySqlHelper.GetDataSet(MySqlHelper.Conn,CommandType.Text,sqlselect1,sp).Tables[0].Rows[0]; //SqlHelper.ExecuteDataRow( System.Data.CommandType.Text, "select * from [Base_Users] where UserName='******' and Password='******'"); if (result == null) //说明不存在 { rc.Msg = "用户不存在"; rc.Code = Code.ERR_Sign; rc.Data = ""; return(rc); } // //只要是一登陆先清除token // MemoryCachingHelper._cache.Remove(result["UserID"].ToString()); // //先判断下缓存中是否存在 这个地方必须拿token去获取 // if(MemoryCachingHelper.Exists(result["UserID"].ToString())) // { // rc.Msg = "成功!"; // rc.Code = Code.SUCCED; // rc.Data = (Token)MemoryCachingHelper.Get(result["UserID"].ToString()); // } // else//不存在才会去生成Token //登陆时先删除 var redisTokenFlag = result["id"].ToString() + result["account"].ToString(); if (RedisStaticHelper.Exists(redisTokenFlag)) { //先删除 var jwtTokenStr = RedisStaticHelper.Get(redisTokenFlag); RedisStaticHelper.Del(jwtTokenStr); RedisStaticHelper.Del(redisTokenFlag); } { //生成JWT //生成token Token tk = new Token(); tk.userName = result["account"].ToString(); tk.userID = result["id"].ToString(); tk.sub = "Client"; //距离上次登录的毫秒数 tk.Timestamp = Convert.ToString(DateTimeToStamp(DateTime.Now)); //DateTime.Now.ToString("yyyyMMddHHmmss"); //token生成规则 用户名 密码 时间戳 MD5加密 //tk.AccessToken = MD5Encrypt32(EmpID, password, tk.Timestamp); //存一下token DateTime UTC = DateTime.UtcNow; Claim[] claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, tk.sub), //Subject, new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //JWT ID,JWT的唯一标识 new Claim(JwtRegisteredClaimNames.Iat, UTC.ToString(), ClaimValueTypes.Integer64), //Issued At,JWT颁发的时间,采用标准unix时间,用于验证过期 }; JwtSecurityToken jwt = new JwtSecurityToken( issuer: "TianTao", //jwt签发者,非必须 audience: tk.userName, //jwt的接收该方,非必须 claims: claims, //声明集合 expires: UTC.AddHours(12), //指定token的生命周期,unix时间戳格式,非必须 signingCredentials: new Microsoft.IdentityModel.Tokens .SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("RayPI's Secret Key")), SecurityAlgorithms.HmacSha256)); //使用私钥进行签名加密 var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); //生成最后的JWT字符串 tk.AccessToken = encodedJwt; // int count = SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, "update [Emp] set Token='" + tk.AccessToken + "' where EmpID='" + EmpID + "' and Pwd='" + password + "'"); // if (count < 1) // { // rc.Msg = "失败,重试"; // rc.Code = Code.SystemError; // rc.Data = ""; // return rc; // } rc.Msg = "成功!"; rc.Code = Code.SUCCED; rc.Data = tk; //将token 存入缓存 //MemoryCachingHelper.addMemoryCache(tk.AccessToken,tk,new TimeSpan(0,10,0),new TimeSpan(0,10,0)); RedisStaticHelper.Set(tk.AccessToken, tk.ToJson()); RedisStaticHelper.Set(tk.userID + tk.userName, tk.AccessToken); } return(rc); } catch (Exception ex) { StaticInfo.Log(ex.ToString()); rc.Msg = "违反了中央八项纪律"; rc.Code = Code.SystemError; rc.Data = ""; return(rc); } }