初始化项目
This commit is contained in:
306
Services/Tool/DateTimeDiff.cs
Normal file
306
Services/Tool/DateTimeDiff.cs
Normal file
@@ -0,0 +1,306 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
public class DateTimeDiff
|
||||
{
|
||||
public DateTimeDiff()
|
||||
{
|
||||
//
|
||||
// TODO: 在此处添加构造函数逻辑
|
||||
//
|
||||
}
|
||||
/// <summary>
|
||||
/// 把秒转换成分钟
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static int SecondToMinute(int Second)
|
||||
{
|
||||
decimal mm = (decimal)((decimal)Second / (decimal)60);
|
||||
return Convert.ToInt32(Math.Ceiling(mm));
|
||||
}
|
||||
/// <summary>
|
||||
/// 计算两个时间的时间间隔
|
||||
/// </summary>
|
||||
/// <param name="DateTimeOld">较早的日期和时间</param>
|
||||
/// <param name="DateTimeNew">较后的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static string DateDiff(DateTime DateTimeOld, DateTime DateTimeNew)
|
||||
{
|
||||
string dateDiff = "";
|
||||
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTimeNew.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
int day = ts.Days;
|
||||
int hou = ts.Hours;
|
||||
int minu = ts.Minutes;
|
||||
int sec = ts.Seconds;
|
||||
if (day > 0)
|
||||
{
|
||||
if (day > 30)
|
||||
{
|
||||
if (day > 364)
|
||||
{
|
||||
dateDiff += day / 365 + "年";
|
||||
}
|
||||
else
|
||||
{
|
||||
dateDiff += day / 30 + "个月";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
dateDiff += day.ToString() + "天";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (hou > 0)
|
||||
{
|
||||
dateDiff += hou.ToString() + "小时";
|
||||
}
|
||||
else
|
||||
{
|
||||
if (minu > 0)
|
||||
{
|
||||
dateDiff += minu.ToString() + "分钟";
|
||||
}
|
||||
else
|
||||
{
|
||||
if (sec > 0)
|
||||
{
|
||||
dateDiff += sec.ToString() + "秒";
|
||||
}
|
||||
else
|
||||
{
|
||||
dateDiff += "0秒";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (DateTimeNew.CompareTo(DateTimeOld) > 0)
|
||||
{
|
||||
dateDiff += "前";
|
||||
}
|
||||
else
|
||||
{
|
||||
dateDiff += "后";
|
||||
}
|
||||
return dateDiff;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回两个日期之间的时间间隔(y:年份间隔、M:月份间隔、d:天数间隔、h:小时间隔、m:分钟间隔、s:秒钟间隔、ms:微秒间隔)
|
||||
/// </summary>
|
||||
/// <param name="Date1">开始日期</param>
|
||||
/// <param name="Date2">结束日期</param>
|
||||
/// <param name="Interval">间隔标志</param>
|
||||
/// <returns>返回间隔标志指定的时间间隔</returns>
|
||||
public static int DateDiff(System.DateTime Date1, System.DateTime Date2, string Interval)
|
||||
{
|
||||
double dblYearLen = 365;//年的长度,365天
|
||||
double dblMonthLen = (365 / 12);//每个月平均的天数
|
||||
System.TimeSpan objT;
|
||||
objT = Date2.Subtract(Date1);
|
||||
switch (Interval)
|
||||
{
|
||||
case "y"://返回日期的年份间隔
|
||||
return System.Convert.ToInt32(objT.Days / dblYearLen);
|
||||
case "M"://返回日期的月份间隔
|
||||
return System.Convert.ToInt32(objT.Days / dblMonthLen);
|
||||
case "d"://返回日期的天数间隔
|
||||
return objT.Days;
|
||||
case "h"://返回日期的小时间隔
|
||||
return objT.Hours;
|
||||
case "m"://返回日期的分钟间隔
|
||||
return objT.Minutes;
|
||||
case "s"://返回日期的秒钟间隔
|
||||
return objT.Seconds;
|
||||
case "ms"://返回时间的微秒间隔
|
||||
return objT.Milliseconds;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///判断是否于1分钟之前
|
||||
/// </summary>
|
||||
/// <param name="DateTimeOld">较早的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static bool DateDiff_minu(DateTime DateTimeOld)
|
||||
{
|
||||
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
int minu = ts.Minutes;
|
||||
if (minu > 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///判断是否于m分钟之前
|
||||
/// </summary>
|
||||
/// <param name="DateTimeOld">较早的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static bool DateDiff_minu(DateTime DateTimeOld, int m)
|
||||
{
|
||||
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
int minu = ts.Minutes;
|
||||
if (minu > m)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public static bool DateDiff_1minu(DateTime DateTimeOld)
|
||||
{
|
||||
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
int minu = ts.Seconds;
|
||||
if (minu > 10)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 与当前时间比较,重载时间比较函数,只有一个参数
|
||||
/// </summary>
|
||||
/// <param name="DateTimeOld">较早的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static string DateDiff(DateTime DateTimeOld)
|
||||
{
|
||||
return DateDiff(DateTimeOld, DateTime.Now);
|
||||
}
|
||||
/// <summary>
|
||||
/// 日期比较,返回精确的几分几秒
|
||||
/// </summary>
|
||||
/// <param name="DateTime1">较早的日期和时间</param>
|
||||
/// <param name="DateTime2">较迟的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static string DateDiff_full(DateTime DateTime1, DateTime DateTime2)
|
||||
{
|
||||
string dateDiff = null;
|
||||
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒";
|
||||
return dateDiff;
|
||||
}
|
||||
/// <summary>
|
||||
/// 时间比较,返回精确的几秒
|
||||
/// </summary>
|
||||
/// <param name="DateTime1">较早的日期和时间</param>
|
||||
/// <param name="DateTime2">较迟的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static int DateDiff_Sec(DateTime DateTime1, DateTime DateTime2)
|
||||
{
|
||||
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
int dateDiff = ts.Days * 86400 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
|
||||
return dateDiff;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 日期比较
|
||||
/// </summary>
|
||||
/// <param name="today">当前日期</param>
|
||||
/// <param name="writeDate">输入日期</param>
|
||||
/// <param name="n">比较天数</param>
|
||||
/// <returns>大于天数返回true,小于返回false</returns>
|
||||
public static bool CompareDate(string today, string writeDate, int n)
|
||||
{
|
||||
DateTime Today = Convert.ToDateTime(today);
|
||||
DateTime WriteDate = Convert.ToDateTime(writeDate);
|
||||
WriteDate = WriteDate.AddDays(n);
|
||||
if (Today >= WriteDate)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
public static string FormatProgress(DateTime StartTime, DateTime EndTime)
|
||||
{
|
||||
|
||||
|
||||
if (DateTime.Now > DateTime.Parse(EndTime.ToShortDateString() + " 23:59:59"))
|
||||
return "活动结束";
|
||||
else if (DateTime.Now < DateTime.Parse(StartTime.ToShortDateString() + " 0:0:0"))
|
||||
return "即将开始";
|
||||
else
|
||||
{
|
||||
int totalDay = DateTimeDiff.DateDiff(StartTime, EndTime, "d");
|
||||
int inDay = DateTimeDiff.DateDiff(StartTime, DateTime.Now, "d");
|
||||
if ((float)inDay / (float)totalDay < 0.2f)
|
||||
return "刚刚开始";
|
||||
else if ((float)inDay / (float)totalDay >= 0.2f && (float)inDay / (float)totalDay < 0.4)
|
||||
return "正在进行";
|
||||
else if ((float)inDay / (float)totalDay >= 0.4 && (float)inDay / (float)totalDay < 0.6)
|
||||
return "活动过半";
|
||||
else if ((float)inDay / (float)totalDay > 0.6 && (float)inDay / (float)totalDay <= 0.8)
|
||||
return "进入尾声";
|
||||
else
|
||||
return "即将结束";
|
||||
}
|
||||
}
|
||||
|
||||
// 时间戳转为C#格式时间
|
||||
public static DateTime StampToDateTime(string timeStamp)
|
||||
{
|
||||
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
||||
long lTime = long.Parse(timeStamp + "0000000");
|
||||
TimeSpan toNow = new TimeSpan(lTime);
|
||||
|
||||
return dateTimeStart.Add(toNow);
|
||||
}
|
||||
|
||||
// DateTime时间格式转换为Unix时间戳格式
|
||||
public static double DateTimeToStamp(System.DateTime time)
|
||||
{
|
||||
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
|
||||
return (time - startTime).TotalMilliseconds;
|
||||
}
|
||||
/// <summary>
|
||||
///判断是否于多少分钟之前
|
||||
/// </summary>
|
||||
/// <param name="DateTimeOld">较早的日期和时间</param>
|
||||
/// <returns></returns>
|
||||
public static bool allDateDiff_minu(DateTime DateTimeOld, int m)
|
||||
{
|
||||
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
|
||||
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
|
||||
TimeSpan ts = ts1.Subtract(ts2).Duration();
|
||||
int minu = ts.Minutes;
|
||||
if (minu > m)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
336
Services/Tool/HttpRequestHelp.cs
Normal file
336
Services/Tool/HttpRequestHelp.cs
Normal file
@@ -0,0 +1,336 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Models;
|
||||
using Models.ApiModei;
|
||||
using Models.ModelItems;
|
||||
using Newtonsoft.Json;
|
||||
using Services.Manager;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
public class HttpRequestHelp
|
||||
{
|
||||
//巫工Api
|
||||
static string Url = "https://www.boonlive-rcu.com/api/"; // 注释掉巫工API 改为宝来威 "https://pms.boonlive-rcu.com/api/";
|
||||
static string Key = "blw_ws@2015";
|
||||
/// <summary>
|
||||
/// 根据MAC获取主机
|
||||
/// </summary>
|
||||
/// <param name="Mac"></param>
|
||||
/// <returns></returns>
|
||||
public static List<Hosts> GetHostByMAC(string Mac)
|
||||
{
|
||||
if (string.IsNullOrEmpty(Mac))
|
||||
return null;
|
||||
var res = new Dictionary<string, dynamic>();
|
||||
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key, mac = Mac }));
|
||||
var resdata = Post<ReturnData<List<HostsAsync>>>(Url + "GetHostByMAC", res);
|
||||
if (resdata != null && resdata.IsSuccess)
|
||||
{
|
||||
List<Hosts> newdata = new List<Hosts>();
|
||||
foreach (var item in resdata.Result)
|
||||
{
|
||||
newdata.Add(new Hosts()
|
||||
{
|
||||
Id = item.ID,
|
||||
HotelID = item.HotelID,
|
||||
Status = item.Status?1:0,
|
||||
HotelName = item.HotelName,
|
||||
Desc = item.Remark,
|
||||
RoomNumber = item.RoomNumber,
|
||||
RoomStatusID = item.RoomStatusID,
|
||||
MAC = item.MAC,
|
||||
});
|
||||
}
|
||||
return newdata;
|
||||
}
|
||||
else
|
||||
{
|
||||
Logs.WriteTimingUDPLog(JsonConvert.SerializeObject(resdata));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取用户信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static List<UserInfo> GetUserList()
|
||||
{
|
||||
var res = new Dictionary<string, dynamic>();
|
||||
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key}));
|
||||
var resdata = Post<ReturnData<List<UserInfoAsync>>>(Url + "GetUserList", res);
|
||||
if (resdata != null && resdata.IsSuccess)
|
||||
{
|
||||
List<UserInfo> newdata = new List<UserInfo>();
|
||||
foreach (var item in resdata.Result)
|
||||
{
|
||||
var s = 2;
|
||||
if(!int.TryParse(item.Sex,out s))
|
||||
{
|
||||
if(item.Sex == "男")
|
||||
{
|
||||
s = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (item.Sex == "女")
|
||||
s = 1;
|
||||
else
|
||||
s = 2;
|
||||
}
|
||||
}
|
||||
if (newdata.FirstOrDefault(x => x.Uid.ToLower() == item.Account.ToLower())!= null) {
|
||||
continue;
|
||||
}
|
||||
newdata.Add(new UserInfo()
|
||||
{
|
||||
OldId = item.ID,
|
||||
IsImport = 1,
|
||||
IsValid = item.ActiveIndicator?0:1,
|
||||
HotelGroupID = item.SysHotelGroupID,
|
||||
HotelID = item.HotelID,
|
||||
CreateTime = item.CreatedDate,
|
||||
Desc = item.Remark,
|
||||
Sex = s,
|
||||
Uid = item.Account,
|
||||
Pwd = item.Password,
|
||||
EndTime = item.CreatedDate.AddMonths(2)
|
||||
});
|
||||
}
|
||||
return newdata;
|
||||
}else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 写入mac地址
|
||||
/// </summary>
|
||||
/// <param name="hotels"></param>
|
||||
/// <param name="Mac"></param>
|
||||
/// <param name="roomNumber"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SetHostMAC(int hotelsid, string Mac,string roomNumber)
|
||||
{
|
||||
// code”:“酒店编码,我司提供,例如:1001”, “creatDate”:“日期,我司提供,例如:2016 - 09 - 05”, “roomNumber”:“房号,如:8888”,
|
||||
//深圳市宝来威智能科技有限公司 第 20页 共 22页 “mac”:“mac 地址,如:34 - D0 - B8 - 1F - 02 - 15”
|
||||
var hotels = new Hotels();
|
||||
|
||||
hotels = SqlSugarBase.Db.Queryable<Hotels>().First(x => x.Id == hotelsid);
|
||||
if (hotels == null)
|
||||
return false;
|
||||
var res = new Dictionary<string, dynamic>();
|
||||
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key, roomNumber= roomNumber, mac = Mac, code = hotels.Code, creatDate = hotels.CreateTime.ToString("yyyy-MM-dd") }));
|
||||
var resdata = Post<ReturnData<string>>(Url + "SetHostMAC", res);
|
||||
if (resdata == null)
|
||||
return false;
|
||||
return resdata.IsSuccess && resdata.Result.Contains("成功");
|
||||
}
|
||||
/// <summary>
|
||||
/// 房间表主机表信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static List<HostsAdd> GetHosts(int hotelsid)
|
||||
{
|
||||
var hotels = new Hotels();
|
||||
hotels = SqlSugarBase.Db.Queryable<Hotels>().First(x=>x.Id == hotelsid);
|
||||
|
||||
|
||||
|
||||
if (hotels == null || hotels == default(Hotels))
|
||||
return null;
|
||||
var res = new Dictionary<string, dynamic>();
|
||||
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key, code = hotels.Code, creatDate = hotels.CreateTime.ToString("yyyy-MM-dd")}));
|
||||
|
||||
try
|
||||
{
|
||||
var resdata = Post<ReturnData<List<HostsAsync>>>(Url + "GetHostList", res);
|
||||
if (resdata != null && resdata.IsSuccess)
|
||||
{
|
||||
List<HostsAdd> newdata = new List<HostsAdd>();
|
||||
var FaceList = FaceServer.SelfaceSN_HotelID(hotels.Id);
|
||||
foreach (var item in resdata.Result)
|
||||
{
|
||||
var temp = FaceList.FirstOrDefault(x => x.RoomId == item.ID);
|
||||
if (temp == null)
|
||||
temp = new DeviceManage();
|
||||
newdata.Add(new HostsAdd()
|
||||
{
|
||||
Id = item.ID,
|
||||
HotelID = item.HotelID,
|
||||
HotelName = item.HotelName,
|
||||
Status = item.Status ? 1 : 0,
|
||||
Desc = item.Remark,
|
||||
RoomNumber = item.RoomNumber,
|
||||
RoomStatusID = item.RoomStatusID,
|
||||
MAC = item.MAC,
|
||||
FaceSN = temp.SerialNo,
|
||||
FaceStatus = temp.Status,
|
||||
maintainStatus = temp.maintainStatus,
|
||||
RoomTypeID = item.RoomTypeID
|
||||
});
|
||||
}
|
||||
return newdata;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取酒店列表 全部酒店信息
|
||||
/// </summary>
|
||||
public static List<Hotels> GetHotelList() {
|
||||
var res = new Dictionary<string, dynamic>();
|
||||
res.Add("jsonData",JsonConvert.SerializeObject( new{ key= Key }));
|
||||
var resdata = Post<ReturnData<List<HotelsAsync>>>(Url+ "GetHotelList", res);
|
||||
if (resdata!=null && resdata.IsSuccess)
|
||||
{
|
||||
List<Hotels> newdata = new List<Hotels>();
|
||||
foreach (var item in resdata.Result)
|
||||
{
|
||||
newdata.Add(new Hotels() {
|
||||
Id = item.ID,
|
||||
Name = item.Name,
|
||||
Status = item.Status,
|
||||
Desc = item.Remark,
|
||||
CreateTime = item.CreatDate,
|
||||
GroupId = item.SysHotelGroupID,
|
||||
IsApprove = item.IsApprove?1:0,
|
||||
Code = item.Code.ToString()
|
||||
});
|
||||
}
|
||||
return newdata;
|
||||
}
|
||||
//return resdata.Result;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取酒店组 全部酒店组信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static List<HotelGroups> GetHotelGroups()
|
||||
{
|
||||
var res = new Dictionary<string, dynamic>();
|
||||
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key }));
|
||||
var resdata = Post<ReturnData<List<HotelGroups>>>(Url + "GetHotelGroupList", res);
|
||||
if (resdata != null && resdata.IsSuccess)
|
||||
return resdata.Result;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取IP
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <returns></returns>
|
||||
public static dynamic GetIp(string url)
|
||||
{
|
||||
return Get<Data>(url);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取ip的帮助类
|
||||
/// </summary>
|
||||
public class Data
|
||||
{
|
||||
public int status { get; set; }
|
||||
public string t { get; set; }
|
||||
public string set_cache_time { get; set; }
|
||||
public List<dynamic> data { get; set; }
|
||||
}
|
||||
|
||||
public class ReturnData<T>
|
||||
{
|
||||
public bool IsSuccess { get; set; }
|
||||
public T Result{ get; set; }
|
||||
}
|
||||
private static T Get<T>(string url, int Timeout = 10000)
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Method = "GET";
|
||||
request.ContentType = "text/html;charset=UTF-8";
|
||||
request.UserAgent = null;
|
||||
request.Timeout = Timeout;
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
Stream myResponseStream = response.GetResponseStream();
|
||||
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
|
||||
string retString = myStreamReader.ReadToEnd();
|
||||
myStreamReader.Close();
|
||||
myResponseStream.Close();
|
||||
if (!string.IsNullOrEmpty(retString))
|
||||
return JsonConvert.DeserializeObject<T>(retString);
|
||||
else
|
||||
return default(T);
|
||||
}
|
||||
/// <summary>
|
||||
/// 指定Post地址使用Get 方式获取全部字符串
|
||||
/// </summary>
|
||||
/// <param name="url">请求后台地址</param>
|
||||
/// <returns></returns>
|
||||
private static T Post<T>(string url, Dictionary<string, dynamic> dic)
|
||||
{
|
||||
string result = "";
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/x-www-form-urlencoded";
|
||||
#region 添加Post 参数
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int i = 0;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append("&");
|
||||
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
i++;
|
||||
}
|
||||
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
#endregion
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(result))
|
||||
return JsonConvert.DeserializeObject<T>(result);
|
||||
else
|
||||
{
|
||||
Logs.WriteTimingUDPLog(result);
|
||||
return default(T);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelp.WriteExceptionLog(ex);
|
||||
return default(T);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
53
Services/Tool/ModelHelper.cs
Normal file
53
Services/Tool/ModelHelper.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
/// <summary>
|
||||
/// 实体帮助
|
||||
/// </summary>
|
||||
public static class ModelHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取实体属性名
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetModelPropertyName<T>() where T : class, new()
|
||||
{
|
||||
string nameStr = "";
|
||||
|
||||
foreach (PropertyInfo pi in (new T()).GetType().GetProperties())
|
||||
{
|
||||
//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
|
||||
var name = pi.Name;
|
||||
//var value = pi.GetValue(list, null);//用pi.GetValue获得值
|
||||
//var type = value?.GetType() ?? typeof(object);//获得属性的类型
|
||||
|
||||
nameStr += "`" + name + "`,";
|
||||
}
|
||||
return nameStr.Substring(0, nameStr.Length - 1);//nameStr; 去除最后一个逗号
|
||||
}
|
||||
|
||||
public static List<Dictionary<string, object>> TableToRow(DataTable tbl)
|
||||
{
|
||||
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
|
||||
foreach (DataRow Row in tbl.Rows)//循环行
|
||||
{
|
||||
Dictionary<string, object> row = new Dictionary<string, object>();
|
||||
for (int i = 0; i < Row.ItemArray.Length; i++)
|
||||
{
|
||||
row.Add(tbl.Columns[i].ColumnName, Row[i].ToString());
|
||||
}
|
||||
rows.Add(row);
|
||||
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
995
Services/Tool/RSAPwd.cs
Normal file
995
Services/Tool/RSAPwd.cs
Normal file
@@ -0,0 +1,995 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
#region rsa加密
|
||||
public class RSA
|
||||
{
|
||||
/// <summary>
|
||||
/// 导出XML格式密钥对,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
|
||||
/// </summary>
|
||||
public string ToXML(bool convertToPublic = false)
|
||||
{
|
||||
return rsa.ToXmlString(!rsa.PublicOnly && !convertToPublic);
|
||||
}
|
||||
/// <summary>
|
||||
/// 将密钥对导出成PEM对象,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
|
||||
/// </summary>
|
||||
public RSA_PEM ToPEM(bool convertToPublic = false)
|
||||
{
|
||||
return new RSA_PEM(rsa, convertToPublic);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 加密字符串(utf-8),出错抛异常
|
||||
/// </summary>
|
||||
public string Encode(string str)
|
||||
{
|
||||
return Convert.ToBase64String(Encode(Encoding.UTF8.GetBytes(str)));
|
||||
}
|
||||
/// <summary>
|
||||
/// 加密数据,出错抛异常
|
||||
/// </summary>
|
||||
public byte[] Encode(byte[] data)
|
||||
{
|
||||
int blockLen = rsa.KeySize / 8 - 11;
|
||||
if (data.Length <= blockLen)
|
||||
{
|
||||
return rsa.Encrypt(data, false);
|
||||
}
|
||||
|
||||
using (var dataStream = new MemoryStream(data))
|
||||
using (var enStream = new MemoryStream())
|
||||
{
|
||||
Byte[] buffer = new Byte[blockLen];
|
||||
int len = dataStream.Read(buffer, 0, blockLen);
|
||||
|
||||
while (len > 0)
|
||||
{
|
||||
Byte[] block = new Byte[len];
|
||||
Array.Copy(buffer, 0, block, 0, len);
|
||||
|
||||
Byte[] enBlock = rsa.Encrypt(block, false);
|
||||
enStream.Write(enBlock, 0, enBlock.Length);
|
||||
|
||||
len = dataStream.Read(buffer, 0, blockLen);
|
||||
}
|
||||
|
||||
return enStream.ToArray();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 解密字符串(utf-8),解密异常返回null
|
||||
/// </summary>
|
||||
public string DecodeOrNull(string str)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] byts = null;
|
||||
try { byts = Convert.FromBase64String(str); } catch { }
|
||||
if (byts == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var val = DecodeOrNull(byts);
|
||||
if (val == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return Encoding.UTF8.GetString(val);
|
||||
}
|
||||
/// <summary>
|
||||
/// 解密数据,解密异常返回null
|
||||
/// </summary>
|
||||
public byte[] DecodeOrNull(byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
int blockLen = rsa.KeySize / 8;
|
||||
if (data.Length <= blockLen)
|
||||
{
|
||||
return rsa.Decrypt(data, false);
|
||||
}
|
||||
|
||||
using (var dataStream = new MemoryStream(data))
|
||||
using (var deStream = new MemoryStream())
|
||||
{
|
||||
Byte[] buffer = new Byte[blockLen];
|
||||
int len = dataStream.Read(buffer, 0, blockLen);
|
||||
|
||||
while (len > 0)
|
||||
{
|
||||
Byte[] block = new Byte[len];
|
||||
Array.Copy(buffer, 0, block, 0, len);
|
||||
|
||||
Byte[] deBlock = rsa.Decrypt(block, false);
|
||||
deStream.Write(deBlock, 0, deBlock.Length);
|
||||
|
||||
len = dataStream.Read(buffer, 0, blockLen);
|
||||
}
|
||||
|
||||
return deStream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 对str进行签名,并指定hash算法(如:SHA256)
|
||||
/// </summary>
|
||||
public string Sign(string hash, string str)
|
||||
{
|
||||
return Convert.ToBase64String(Sign(hash, Encoding.UTF8.GetBytes(str)));
|
||||
}
|
||||
/// <summary>
|
||||
/// 对data进行签名,并指定hash算法(如:SHA256)
|
||||
/// </summary>
|
||||
public byte[] Sign(string hash, byte[] data)
|
||||
{
|
||||
return rsa.SignData(data, hash);
|
||||
}
|
||||
/// <summary>
|
||||
/// 验证字符串str的签名是否是sgin,并指定hash算法(如:SHA256)
|
||||
/// </summary>
|
||||
public bool Verify(string hash, string sgin, string str)
|
||||
{
|
||||
byte[] byts = null;
|
||||
try { byts = Convert.FromBase64String(sgin); } catch { }
|
||||
if (byts == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return Verify(hash, byts, Encoding.UTF8.GetBytes(str));
|
||||
}
|
||||
/// <summary>
|
||||
/// 验证data的签名是否是sgin,并指定hash算法(如:SHA256)
|
||||
/// </summary>
|
||||
public bool Verify(string hash, byte[] sgin, byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return rsa.VerifyData(data, hash, sgin);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private RSACryptoServiceProvider rsa;
|
||||
/// <summary>
|
||||
/// 最底层的RSACryptoServiceProvider对象
|
||||
/// </summary>
|
||||
public RSACryptoServiceProvider RSAObject
|
||||
{
|
||||
get
|
||||
{
|
||||
return rsa;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 密钥位数
|
||||
/// </summary>
|
||||
public int KeySize
|
||||
{
|
||||
get
|
||||
{
|
||||
return rsa.KeySize;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否包含私钥
|
||||
/// </summary>
|
||||
public bool HasPrivate
|
||||
{
|
||||
get
|
||||
{
|
||||
return !rsa.PublicOnly;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用指定密钥大小创建一个新的RSA,出错抛异常
|
||||
/// </summary>
|
||||
public RSA(int keySize)
|
||||
{
|
||||
var rsaParams = new CspParameters();
|
||||
rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
|
||||
rsa = new RSACryptoServiceProvider(keySize, rsaParams);
|
||||
}
|
||||
/// <summary>
|
||||
/// 通过指定的密钥,创建一个RSA,xml内可以只包含一个公钥或私钥,或都包含,出错抛异常
|
||||
/// </summary>
|
||||
public RSA(string xml)
|
||||
{
|
||||
var rsaParams = new CspParameters();
|
||||
rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
|
||||
rsa = new RSACryptoServiceProvider(rsaParams);
|
||||
|
||||
rsa.FromXmlString(xml);
|
||||
}
|
||||
/// <summary>
|
||||
/// 通过一个pem文件创建RSA,pem为公钥或私钥,出错抛异常
|
||||
/// </summary>
|
||||
public RSA(string pem, bool noop)
|
||||
{
|
||||
rsa = RSA_PEM.FromPEM(pem).GetRSA();
|
||||
}
|
||||
/// <summary>
|
||||
/// 通过一个pem对象创建RSA,pem为公钥或私钥,出错抛异常
|
||||
/// </summary>
|
||||
public RSA(RSA_PEM pem)
|
||||
{
|
||||
rsa = pem.GetRSA();
|
||||
}
|
||||
/// <summary>
|
||||
/// 本方法会先生成RSA_PEM再创建RSA:通过公钥指数和私钥指数构造一个PEM,会反推计算出P、Q但和原始生成密钥的P、Q极小可能相同
|
||||
/// 注意:所有参数首字节如果是0,必须先去掉
|
||||
/// 出错将会抛出异常
|
||||
/// </summary>
|
||||
/// <param name="modulus">必须提供模数</param>
|
||||
/// <param name="exponent">必须提供公钥指数</param>
|
||||
/// <param name="dOrNull">私钥指数可以不提供,导出的PEM就只包含公钥</param>
|
||||
public RSA(byte[] modulus, byte[] exponent, byte[] dOrNull)
|
||||
{
|
||||
rsa = new RSA_PEM(modulus, exponent, dOrNull).GetRSA();
|
||||
}
|
||||
/// <summary>
|
||||
/// 本方法会先生成RSA_PEM再创建RSA:通过全量的PEM字段数据构造一个PEM,除了模数modulus和公钥指数exponent必须提供外,其他私钥指数信息要么全部提供,要么全部不提供(导出的PEM就只包含公钥)
|
||||
/// 注意:所有参数首字节如果是0,必须先去掉
|
||||
/// </summary>
|
||||
public RSA(byte[] modulus, byte[] exponent, byte[] d, byte[] p, byte[] q, byte[] dp, byte[] dq, byte[] inverseQ)
|
||||
{
|
||||
rsa = new RSA_PEM(modulus, exponent, d, p, q, dp, dq, inverseQ).GetRSA();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
public class RSA_PEM
|
||||
{
|
||||
/// <summary>
|
||||
/// modulus 模数n,公钥、私钥都有
|
||||
/// </summary>
|
||||
public byte[] Key_Modulus;
|
||||
/// <summary>
|
||||
/// publicExponent 公钥指数e,公钥、私钥都有
|
||||
/// </summary>
|
||||
public byte[] Key_Exponent;
|
||||
/// <summary>
|
||||
/// privateExponent 私钥指数d,只有私钥的时候才有
|
||||
/// </summary>
|
||||
public byte[] Key_D;
|
||||
|
||||
//以下参数只有私钥才有 https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.rsaparameters?redirectedfrom=MSDN&view=netframework-4.8
|
||||
/// <summary>
|
||||
/// prime1
|
||||
/// </summary>
|
||||
public byte[] Val_P;
|
||||
/// <summary>
|
||||
/// prime2
|
||||
/// </summary>
|
||||
public byte[] Val_Q;
|
||||
/// <summary>
|
||||
/// exponent1
|
||||
/// </summary>
|
||||
public byte[] Val_DP;
|
||||
/// <summary>
|
||||
/// exponent2
|
||||
/// </summary>
|
||||
public byte[] Val_DQ;
|
||||
/// <summary>
|
||||
/// coefficient
|
||||
/// </summary>
|
||||
public byte[] Val_InverseQ;
|
||||
|
||||
private RSA_PEM() { }
|
||||
|
||||
/// <summary>
|
||||
/// 通过RSA中的公钥和私钥构造一个PEM,如果convertToPublic含私钥的RSA将只读取公钥,仅含公钥的RSA不受影响
|
||||
/// </summary>
|
||||
public RSA_PEM(RSACryptoServiceProvider rsa, bool convertToPublic = false)
|
||||
{
|
||||
var isPublic = convertToPublic || rsa.PublicOnly;
|
||||
var param = rsa.ExportParameters(!isPublic);
|
||||
|
||||
Key_Modulus = param.Modulus;
|
||||
Key_Exponent = param.Exponent;
|
||||
|
||||
if (!isPublic)
|
||||
{
|
||||
Key_D = param.D;
|
||||
|
||||
Val_P = param.P;
|
||||
Val_Q = param.Q;
|
||||
Val_DP = param.DP;
|
||||
Val_DQ = param.DQ;
|
||||
Val_InverseQ = param.InverseQ;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 通过全量的PEM字段数据构造一个PEM,除了模数modulus和公钥指数exponent必须提供外,其他私钥指数信息要么全部提供,要么全部不提供(导出的PEM就只包含公钥)
|
||||
/// 注意:所有参数首字节如果是0,必须先去掉
|
||||
/// </summary>
|
||||
public RSA_PEM(byte[] modulus, byte[] exponent, byte[] d, byte[] p, byte[] q, byte[] dp, byte[] dq, byte[] inverseQ)
|
||||
{
|
||||
Key_Modulus = modulus;
|
||||
Key_Exponent = exponent;
|
||||
Key_D = BigL(d, modulus.Length);
|
||||
|
||||
int keyLen = modulus.Length / 2;
|
||||
Val_P = BigL(p, keyLen);
|
||||
Val_Q = BigL(q, keyLen);
|
||||
Val_DP = BigL(dp, keyLen);
|
||||
Val_DQ = BigL(dq, keyLen);
|
||||
Val_InverseQ = BigL(inverseQ, keyLen);
|
||||
}
|
||||
/// <summary>
|
||||
/// 通过公钥指数和私钥指数构造一个PEM,会反推计算出P、Q但和原始生成密钥的P、Q极小可能相同
|
||||
/// 注意:所有参数首字节如果是0,必须先去掉
|
||||
/// 出错将会抛出异常
|
||||
/// </summary>
|
||||
/// <param name="modulus">必须提供模数</param>
|
||||
/// <param name="exponent">必须提供公钥指数</param>
|
||||
/// <param name="dOrNull">私钥指数可以不提供,导出的PEM就只包含公钥</param>
|
||||
public RSA_PEM(byte[] modulus, byte[] exponent, byte[] dOrNull)
|
||||
{
|
||||
Key_Modulus = modulus;//modulus
|
||||
Key_Exponent = exponent;//publicExponent
|
||||
|
||||
if (dOrNull != null)
|
||||
{
|
||||
Key_D = BigL(dOrNull, modulus.Length);//privateExponent
|
||||
|
||||
//反推P、Q
|
||||
BigInteger n = BigX(modulus);
|
||||
BigInteger e = BigX(exponent);
|
||||
BigInteger d = BigX(dOrNull);
|
||||
BigInteger p = FindFactor(e, d, n);
|
||||
BigInteger q = n / p;
|
||||
if (p.CompareTo(q) > 0)
|
||||
{
|
||||
BigInteger t = p;
|
||||
p = q;
|
||||
q = t;
|
||||
}
|
||||
BigInteger exp1 = d % (p - BigInteger.One);
|
||||
BigInteger exp2 = d % (q - BigInteger.One);
|
||||
BigInteger coeff = BigInteger.ModPow(q, p - 2, p);
|
||||
|
||||
int keyLen = modulus.Length / 2;
|
||||
Val_P = BigL(BigB(p), keyLen);//prime1
|
||||
Val_Q = BigL(BigB(q), keyLen);//prime2
|
||||
Val_DP = BigL(BigB(exp1), keyLen);//exponent1
|
||||
Val_DQ = BigL(BigB(exp2), keyLen);//exponent2
|
||||
Val_InverseQ = BigL(BigB(coeff), keyLen);//coefficient
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 密钥位数
|
||||
/// </summary>
|
||||
public int KeySize
|
||||
{
|
||||
get
|
||||
{
|
||||
return Key_Modulus.Length * 8;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否包含私钥
|
||||
/// </summary>
|
||||
public bool HasPrivate
|
||||
{
|
||||
get
|
||||
{
|
||||
return Key_D != null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 将PEM中的公钥私钥转成RSA对象,如果未提供私钥,RSA中就只包含公钥
|
||||
/// </summary>
|
||||
public RSACryptoServiceProvider GetRSA()
|
||||
{
|
||||
var rsaParams = new CspParameters();
|
||||
rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
|
||||
var rsa = new RSACryptoServiceProvider(rsaParams);
|
||||
|
||||
var param = new RSAParameters();
|
||||
param.Modulus = Key_Modulus;
|
||||
param.Exponent = Key_Exponent;
|
||||
if (Key_D != null)
|
||||
{
|
||||
param.D = Key_D;
|
||||
param.P = Val_P;
|
||||
param.Q = Val_Q;
|
||||
param.DP = Val_DP;
|
||||
param.DQ = Val_DQ;
|
||||
param.InverseQ = Val_InverseQ;
|
||||
}
|
||||
rsa.ImportParameters(param);
|
||||
return rsa;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转成正整数,如果是负数,需要加前导0转成正整数
|
||||
/// </summary>
|
||||
static public BigInteger BigX(byte[] bigb)
|
||||
{
|
||||
if (bigb[0] > 0x7F)
|
||||
{
|
||||
byte[] c = new byte[bigb.Length + 1];
|
||||
Array.Copy(bigb, 0, c, 1, bigb.Length);
|
||||
bigb = c;
|
||||
}
|
||||
return new BigInteger(bigb.Reverse().ToArray());//C#的二进制是反的
|
||||
}
|
||||
/// <summary>
|
||||
/// BigInt导出byte整数首字节>0x7F的会加0前导,保证正整数,因此需要去掉0
|
||||
/// </summary>
|
||||
static public byte[] BigB(BigInteger bigx)
|
||||
{
|
||||
byte[] val = bigx.ToByteArray().Reverse().ToArray();//C#的二进制是反的
|
||||
if (val[0] == 0)
|
||||
{
|
||||
byte[] c = new byte[val.Length - 1];
|
||||
Array.Copy(val, 1, c, 0, c.Length);
|
||||
val = c;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
/// <summary>
|
||||
/// 某些密钥参数可能会少一位(32个byte只有31个,目测是密钥生成器的问题,只在c#生成的密钥中发现这种参数,java中生成的密钥没有这种现象),直接修正一下就行;这个问题与BigB有本质区别,不能动BigB
|
||||
/// </summary>
|
||||
static public byte[] BigL(byte[] bytes, int keyLen)
|
||||
{
|
||||
if (keyLen - bytes.Length == 1)
|
||||
{
|
||||
byte[] c = new byte[bytes.Length + 1];
|
||||
Array.Copy(bytes, 0, c, 1, bytes.Length);
|
||||
bytes = c;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
/// <summary>
|
||||
/// 由n e d 反推 P Q
|
||||
/// 资料: https://stackoverflow.com/questions/43136036/how-to-get-a-rsaprivatecrtkey-from-a-rsaprivatekey
|
||||
/// https://v2ex.com/t/661736
|
||||
/// </summary>
|
||||
static private BigInteger FindFactor(BigInteger e, BigInteger d, BigInteger n)
|
||||
{
|
||||
BigInteger edMinus1 = e * d - BigInteger.One;
|
||||
int s = -1;
|
||||
if (edMinus1 != BigInteger.Zero)
|
||||
{
|
||||
s = (int)(BigInteger.Log(edMinus1 & -edMinus1) / BigInteger.Log(2));
|
||||
}
|
||||
BigInteger t = edMinus1 >> s;
|
||||
|
||||
long now = DateTime.Now.Ticks;
|
||||
for (int aInt = 2; true; aInt++)
|
||||
{
|
||||
if (aInt % 10 == 0 && DateTime.Now.Ticks - now > 3000 * 10000)
|
||||
{
|
||||
throw new Exception("推算RSA.P超时");//测试最多循环2次,1024位的速度很快 8ms
|
||||
}
|
||||
|
||||
BigInteger aPow = BigInteger.ModPow(new BigInteger(aInt), t, n);
|
||||
for (int i = 1; i <= s; i++)
|
||||
{
|
||||
if (aPow == BigInteger.One)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (aPow == n - BigInteger.One)
|
||||
{
|
||||
break;
|
||||
}
|
||||
BigInteger aPowSquared = aPow * aPow % n;
|
||||
if (aPowSquared == BigInteger.One)
|
||||
{
|
||||
return BigInteger.GreatestCommonDivisor(aPow - BigInteger.One, n);
|
||||
}
|
||||
aPow = aPowSquared;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 用PEM格式密钥对创建RSA,支持PKCS#1、PKCS#8格式的PEM
|
||||
/// 出错将会抛出异常
|
||||
/// </summary>
|
||||
static public RSA_PEM FromPEM(string pem)
|
||||
{
|
||||
RSA_PEM param = new RSA_PEM();
|
||||
|
||||
var base64 = _PEMCode.Replace(pem, "");
|
||||
byte[] data = null;
|
||||
try { data = Convert.FromBase64String(base64); } catch { }
|
||||
if (data == null)
|
||||
{
|
||||
throw new Exception("PEM内容无效");
|
||||
}
|
||||
var idx = 0;
|
||||
|
||||
//读取长度
|
||||
Func<byte, int> readLen = (first) => {
|
||||
if (data[idx] == first)
|
||||
{
|
||||
idx++;
|
||||
if (data[idx] == 0x81)
|
||||
{
|
||||
idx++;
|
||||
return data[idx++];
|
||||
}
|
||||
else if (data[idx] == 0x82)
|
||||
{
|
||||
idx++;
|
||||
return (((int)data[idx++]) << 8) + data[idx++];
|
||||
}
|
||||
else if (data[idx] < 0x80)
|
||||
{
|
||||
return data[idx++];
|
||||
}
|
||||
}
|
||||
throw new Exception("PEM未能提取到数据");
|
||||
};
|
||||
//读取块数据
|
||||
Func<byte[]> readBlock = () => {
|
||||
var len = readLen(0x02);
|
||||
if (data[idx] == 0x00)
|
||||
{
|
||||
idx++;
|
||||
len--;
|
||||
}
|
||||
var val = new byte[len];
|
||||
for (var i = 0; i < len; i++)
|
||||
{
|
||||
val[i] = data[idx + i];
|
||||
}
|
||||
idx += len;
|
||||
return val;
|
||||
};
|
||||
//比较data从idx位置开始是否是byts内容
|
||||
Func<byte[], bool> eq = (byts) => {
|
||||
for (var i = 0; i < byts.Length; i++, idx++)
|
||||
{
|
||||
if (idx >= data.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (byts[i] != data[idx])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
if (pem.Contains("PUBLIC KEY"))
|
||||
{
|
||||
/****使用公钥****/
|
||||
//读取数据总长度
|
||||
readLen(0x30);
|
||||
|
||||
//检测PKCS8
|
||||
var idx2 = idx;
|
||||
if (eq(_SeqOID))
|
||||
{
|
||||
//读取1长度
|
||||
readLen(0x03);
|
||||
idx++;//跳过0x00
|
||||
//读取2长度
|
||||
readLen(0x30);
|
||||
}
|
||||
else
|
||||
{
|
||||
idx = idx2;
|
||||
}
|
||||
|
||||
//Modulus
|
||||
param.Key_Modulus = readBlock();
|
||||
|
||||
//Exponent
|
||||
param.Key_Exponent = readBlock();
|
||||
}
|
||||
else if (pem.Contains("PRIVATE KEY"))
|
||||
{
|
||||
/****使用私钥****/
|
||||
//读取数据总长度
|
||||
readLen(0x30);
|
||||
|
||||
//读取版本号
|
||||
if (!eq(_Ver))
|
||||
{
|
||||
throw new Exception("PEM未知版本");
|
||||
}
|
||||
|
||||
//检测PKCS8
|
||||
var idx2 = idx;
|
||||
if (eq(_SeqOID))
|
||||
{
|
||||
//读取1长度
|
||||
readLen(0x04);
|
||||
//读取2长度
|
||||
readLen(0x30);
|
||||
|
||||
//读取版本号
|
||||
if (!eq(_Ver))
|
||||
{
|
||||
throw new Exception("PEM版本无效");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
idx = idx2;
|
||||
}
|
||||
|
||||
//读取数据
|
||||
param.Key_Modulus = readBlock();
|
||||
param.Key_Exponent = readBlock();
|
||||
int keyLen = param.Key_Modulus.Length;
|
||||
param.Key_D = BigL(readBlock(), keyLen);
|
||||
keyLen = keyLen / 2;
|
||||
param.Val_P = BigL(readBlock(), keyLen);
|
||||
param.Val_Q = BigL(readBlock(), keyLen);
|
||||
param.Val_DP = BigL(readBlock(), keyLen);
|
||||
param.Val_DQ = BigL(readBlock(), keyLen);
|
||||
param.Val_InverseQ = BigL(readBlock(), keyLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("pem需要BEGIN END标头");
|
||||
}
|
||||
|
||||
return param;
|
||||
}
|
||||
static private readonly Regex _PEMCode = new Regex(@"--+.+?--+|\s+");
|
||||
static private readonly byte[] _SeqOID = new byte[] { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
|
||||
static private readonly byte[] _Ver = new byte[] { 0x02, 0x01, 0x00 };
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 将RSA中的密钥对转换成PEM PKCS#1格式
|
||||
/// 。convertToPublic:等于true时含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
|
||||
/// 。公钥如:-----BEGIN RSA PUBLIC KEY-----,私钥如:-----BEGIN RSA PRIVATE KEY-----
|
||||
/// 。似乎导出PKCS#1公钥用的比较少,PKCS#8的公钥用的多些,私钥#1#8都差不多
|
||||
/// </summary>
|
||||
public string ToPEM_PKCS1(bool convertToPublic = false)
|
||||
{
|
||||
return ToPEM(convertToPublic, false, false);
|
||||
}
|
||||
/// <summary>
|
||||
/// 将RSA中的密钥对转换成PEM PKCS#8格式
|
||||
/// 。convertToPublic:等于true时含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
|
||||
/// 。公钥如:-----BEGIN PUBLIC KEY-----,私钥如:-----BEGIN PRIVATE KEY-----
|
||||
/// </summary>
|
||||
public string ToPEM_PKCS8(bool convertToPublic = false)
|
||||
{
|
||||
return ToPEM(convertToPublic, true, true);
|
||||
}
|
||||
/// <summary>
|
||||
/// 将RSA中的密钥对转换成PEM格式
|
||||
/// 。convertToPublic:等于true时含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
|
||||
/// 。privateUsePKCS8:私钥的返回格式,等于true时返回PKCS#8格式(-----BEGIN PRIVATE KEY-----),否则返回PKCS#1格式(-----BEGIN RSA PRIVATE KEY-----),返回公钥时此参数无效;两种格式使用都比较常见
|
||||
/// 。publicUsePKCS8:公钥的返回格式,等于true时返回PKCS#8格式(-----BEGIN PUBLIC KEY-----),否则返回PKCS#1格式(-----BEGIN RSA PUBLIC KEY-----),返回私钥时此参数无效;一般用的多的是true PKCS#8格式公钥,PKCS#1格式似乎比较少见公钥
|
||||
/// </summary>
|
||||
public string ToPEM(bool convertToPublic, bool privateUsePKCS8, bool publicUsePKCS8)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
//写入一个长度字节码
|
||||
Action<int> writeLenByte = (len) => {
|
||||
if (len < 0x80)
|
||||
{
|
||||
ms.WriteByte((byte)len);
|
||||
}
|
||||
else if (len <= 0xff)
|
||||
{
|
||||
ms.WriteByte(0x81);
|
||||
ms.WriteByte((byte)len);
|
||||
}
|
||||
else
|
||||
{
|
||||
ms.WriteByte(0x82);
|
||||
ms.WriteByte((byte)(len >> 8 & 0xff));
|
||||
ms.WriteByte((byte)(len & 0xff));
|
||||
}
|
||||
};
|
||||
//写入一块数据
|
||||
Action<byte[]> writeBlock = (byts) => {
|
||||
var addZero = (byts[0] >> 4) >= 0x8;
|
||||
ms.WriteByte(0x02);
|
||||
var len = byts.Length + (addZero ? 1 : 0);
|
||||
writeLenByte(len);
|
||||
|
||||
if (addZero)
|
||||
{
|
||||
ms.WriteByte(0x00);
|
||||
}
|
||||
ms.Write(byts, 0, byts.Length);
|
||||
};
|
||||
//根据后续内容长度写入长度数据
|
||||
Func<int, byte[], byte[]> writeLen = (index, byts) => {
|
||||
var len = byts.Length - index;
|
||||
|
||||
ms.SetLength(0);
|
||||
ms.Write(byts, 0, index);
|
||||
writeLenByte(len);
|
||||
ms.Write(byts, index, len);
|
||||
|
||||
return ms.ToArray();
|
||||
};
|
||||
Action<MemoryStream, byte[]> writeAll = (stream, byts) => {
|
||||
stream.Write(byts, 0, byts.Length);
|
||||
};
|
||||
Func<string, int, string> TextBreak = (text, line) => {
|
||||
var idx = 0;
|
||||
var len = text.Length;
|
||||
var str = new StringBuilder();
|
||||
while (idx < len)
|
||||
{
|
||||
if (idx > 0)
|
||||
{
|
||||
str.Append('\n');
|
||||
}
|
||||
if (idx + line >= len)
|
||||
{
|
||||
str.Append(text.Substring(idx));
|
||||
}
|
||||
else
|
||||
{
|
||||
str.Append(text.Substring(idx, line));
|
||||
}
|
||||
idx += line;
|
||||
}
|
||||
return str.ToString();
|
||||
};
|
||||
|
||||
|
||||
if (Key_D == null || convertToPublic)
|
||||
{
|
||||
/****生成公钥****/
|
||||
|
||||
//写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入
|
||||
ms.WriteByte(0x30);
|
||||
var index1 = (int)ms.Length;
|
||||
|
||||
//PKCS8 多一段数据
|
||||
int index2 = -1, index3 = -1;
|
||||
if (publicUsePKCS8)
|
||||
{
|
||||
//固定内容
|
||||
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
|
||||
writeAll(ms, _SeqOID);
|
||||
|
||||
//从0x00开始的后续长度
|
||||
ms.WriteByte(0x03);
|
||||
index2 = (int)ms.Length;
|
||||
ms.WriteByte(0x00);
|
||||
|
||||
//后续内容长度
|
||||
ms.WriteByte(0x30);
|
||||
index3 = (int)ms.Length;
|
||||
}
|
||||
|
||||
//写入Modulus
|
||||
writeBlock(Key_Modulus);
|
||||
|
||||
//写入Exponent
|
||||
writeBlock(Key_Exponent);
|
||||
|
||||
|
||||
//计算空缺的长度
|
||||
var byts = ms.ToArray();
|
||||
|
||||
if (index2 != -1)
|
||||
{
|
||||
byts = writeLen(index3, byts);
|
||||
byts = writeLen(index2, byts);
|
||||
}
|
||||
byts = writeLen(index1, byts);
|
||||
|
||||
|
||||
var flag = " PUBLIC KEY";
|
||||
if (!publicUsePKCS8)
|
||||
{
|
||||
flag = " RSA" + flag;
|
||||
}
|
||||
return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
|
||||
}
|
||||
else
|
||||
{
|
||||
/****生成私钥****/
|
||||
|
||||
//写入总字节数,后续写入
|
||||
ms.WriteByte(0x30);
|
||||
int index1 = (int)ms.Length;
|
||||
|
||||
//写入版本号
|
||||
writeAll(ms, _Ver);
|
||||
|
||||
//PKCS8 多一段数据
|
||||
int index2 = -1, index3 = -1;
|
||||
if (privateUsePKCS8)
|
||||
{
|
||||
//固定内容
|
||||
writeAll(ms, _SeqOID);
|
||||
|
||||
//后续内容长度
|
||||
ms.WriteByte(0x04);
|
||||
index2 = (int)ms.Length;
|
||||
|
||||
//后续内容长度
|
||||
ms.WriteByte(0x30);
|
||||
index3 = (int)ms.Length;
|
||||
|
||||
//写入版本号
|
||||
writeAll(ms, _Ver);
|
||||
}
|
||||
|
||||
//写入数据
|
||||
writeBlock(Key_Modulus);
|
||||
writeBlock(Key_Exponent);
|
||||
writeBlock(Key_D);
|
||||
writeBlock(Val_P);
|
||||
writeBlock(Val_Q);
|
||||
writeBlock(Val_DP);
|
||||
writeBlock(Val_DQ);
|
||||
writeBlock(Val_InverseQ);
|
||||
|
||||
|
||||
//计算空缺的长度
|
||||
var byts = ms.ToArray();
|
||||
|
||||
if (index2 != -1)
|
||||
{
|
||||
byts = writeLen(index3, byts);
|
||||
byts = writeLen(index2, byts);
|
||||
}
|
||||
byts = writeLen(index1, byts);
|
||||
|
||||
|
||||
var flag = " PRIVATE KEY";
|
||||
if (!privateUsePKCS8)
|
||||
{
|
||||
flag = " RSA" + flag;
|
||||
}
|
||||
return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 将XML格式密钥转成PEM,支持公钥xml、私钥xml
|
||||
/// 出错将会抛出异常
|
||||
/// </summary>
|
||||
static public RSA_PEM FromXML(string xml)
|
||||
{
|
||||
RSA_PEM rtv = new RSA_PEM();
|
||||
|
||||
Match xmlM = xmlExp.Match(xml);
|
||||
if (!xmlM.Success)
|
||||
{
|
||||
throw new Exception("XML内容不符合要求");
|
||||
}
|
||||
|
||||
Match tagM = xmlTagExp.Match(xmlM.Groups[1].Value);
|
||||
while (tagM.Success)
|
||||
{
|
||||
string tag = tagM.Groups[1].Value;
|
||||
string b64 = tagM.Groups[2].Value;
|
||||
byte[] val = Convert.FromBase64String(b64);
|
||||
switch (tag)
|
||||
{
|
||||
case "Modulus": rtv.Key_Modulus = val; break;
|
||||
case "Exponent": rtv.Key_Exponent = val; break;
|
||||
case "D": rtv.Key_D = val; break;
|
||||
|
||||
case "P": rtv.Val_P = val; break;
|
||||
case "Q": rtv.Val_Q = val; break;
|
||||
case "DP": rtv.Val_DP = val; break;
|
||||
case "DQ": rtv.Val_DQ = val; break;
|
||||
case "InverseQ": rtv.Val_InverseQ = val; break;
|
||||
}
|
||||
tagM = tagM.NextMatch();
|
||||
}
|
||||
|
||||
if (rtv.Key_Modulus == null || rtv.Key_Exponent == null)
|
||||
{
|
||||
throw new Exception("XML公钥丢失");
|
||||
}
|
||||
if (rtv.Key_D != null)
|
||||
{
|
||||
if (rtv.Val_P == null || rtv.Val_Q == null || rtv.Val_DP == null || rtv.Val_DQ == null || rtv.Val_InverseQ == null)
|
||||
{
|
||||
return new RSA_PEM(rtv.Key_Modulus, rtv.Key_Exponent, rtv.Key_D);
|
||||
}
|
||||
}
|
||||
|
||||
return rtv;
|
||||
}
|
||||
static private readonly Regex xmlExp = new Regex("\\s*<RSAKeyValue>([<>\\/\\+=\\w\\s]+)</RSAKeyValue>\\s*");
|
||||
static private readonly Regex xmlTagExp = new Regex("<(.+?)>\\s*([^<]+?)\\s*</");
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 将RSA中的密钥对转换成XML格式
|
||||
/// ,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
|
||||
/// </summary>
|
||||
public string ToXML(bool convertToPublic)
|
||||
{
|
||||
StringBuilder str = new StringBuilder();
|
||||
str.Append("<RSAKeyValue>");
|
||||
str.Append("<Modulus>" + Convert.ToBase64String(Key_Modulus) + "</Modulus>");
|
||||
str.Append("<Exponent>" + Convert.ToBase64String(Key_Exponent) + "</Exponent>");
|
||||
if (Key_D == null || convertToPublic)
|
||||
{
|
||||
/****生成公钥****/
|
||||
//NOOP
|
||||
}
|
||||
else
|
||||
{
|
||||
/****生成私钥****/
|
||||
str.Append("<P>" + Convert.ToBase64String(Val_P) + "</P>");
|
||||
str.Append("<Q>" + Convert.ToBase64String(Val_Q) + "</Q>");
|
||||
str.Append("<DP>" + Convert.ToBase64String(Val_DP) + "</DP>");
|
||||
str.Append("<DQ>" + Convert.ToBase64String(Val_DQ) + "</DQ>");
|
||||
str.Append("<InverseQ>" + Convert.ToBase64String(Val_InverseQ) + "</InverseQ>");
|
||||
str.Append("<D>" + Convert.ToBase64String(Key_D) + "</D>");
|
||||
}
|
||||
str.Append("</RSAKeyValue>");
|
||||
return str.ToString();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
1172
Services/Tool/RedisHelper.cs
Normal file
1172
Services/Tool/RedisHelper.cs
Normal file
File diff suppressed because it is too large
Load Diff
17
Services/Tool/System/ComputerHelp.cs
Normal file
17
Services/Tool/System/ComputerHelp.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
public class ComputerHelp
|
||||
{
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
159
Services/Tool/System/ConfigHelper.cs
Normal file
159
Services/Tool/System/ConfigHelper.cs
Normal file
@@ -0,0 +1,159 @@
|
||||
using Services.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.IO;
|
||||
using System.Web.Configuration;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
/// <summary>
|
||||
/// web.config操作类
|
||||
/// Copyright (C) Maticsoft
|
||||
/// </summary>
|
||||
public sealed class ConfigHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 得到AppSettings中的配置字符串信息
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetConfigString(string key)
|
||||
{
|
||||
string CacheKey = "AppSettings-" + key;
|
||||
object objModel = CacheExtensions.GetCache<object>(CacheKey);
|
||||
if (objModel == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
objModel = ConfigurationManager.AppSettings[key];
|
||||
if (objModel != null)
|
||||
{
|
||||
CacheExtensions.SetCache(CacheKey, objModel, Services.Enums.CacheTimeType.ByHours, 3);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{ }
|
||||
}
|
||||
return objModel.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 得到AppSettings中的配置Bool信息
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static bool GetConfigBool(string key)
|
||||
{
|
||||
bool result = false;
|
||||
string cfgVal = GetConfigString(key);
|
||||
if (null != cfgVal && string.Empty != cfgVal)
|
||||
{
|
||||
try
|
||||
{
|
||||
result = bool.Parse(cfgVal);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Ignore format exceptions.
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// 得到AppSettings中的配置Decimal信息
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static decimal GetConfigDecimal(string key)
|
||||
{
|
||||
decimal result = 0;
|
||||
string cfgVal = GetConfigString(key);
|
||||
if (null != cfgVal && string.Empty != cfgVal)
|
||||
{
|
||||
try
|
||||
{
|
||||
result = decimal.Parse(cfgVal);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Ignore format exceptions.
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// 得到AppSettings中的配置int信息
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static int GetConfigInt(string key)
|
||||
{
|
||||
int result = 0;
|
||||
string cfgVal = GetConfigString(key);
|
||||
if (null != cfgVal && string.Empty != cfgVal)
|
||||
{
|
||||
try
|
||||
{
|
||||
result = int.Parse(cfgVal);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Ignore format exceptions.
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改AppSettings中的配置信息
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static void UpdatetConfig(string key, string value)
|
||||
{
|
||||
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
|
||||
AppSettingsSection objAppSettings = (AppSettingsSection)objConfig.GetSection("appSettings");
|
||||
if (objAppSettings != null)
|
||||
{
|
||||
objAppSettings.Settings[key].Value = value;
|
||||
objConfig.Save();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 加载配置文件 app升级配置文件
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<String, String> loadCfg()
|
||||
{
|
||||
string cfgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
|
||||
+ Path.DirectorySeparatorChar + "appset" + Path.DirectorySeparatorChar + "appconfig.properties";
|
||||
Dictionary<String, String> cfg = new Dictionary<string, string>();
|
||||
using (StreamReader sr = new StreamReader(cfgPath))
|
||||
{
|
||||
while (sr.Peek() >= 0)
|
||||
{
|
||||
string line = sr.ReadLine();
|
||||
if (line.StartsWith("#"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int startInd = line.IndexOf("=");
|
||||
string key = line.Substring(0, startInd);
|
||||
string val = line.Substring(startInd + 1, line.Length - (startInd + 1));
|
||||
if (!cfg.ContainsKey(key) && !string.IsNullOrEmpty(val))
|
||||
{
|
||||
cfg.Add(key, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
}
|
||||
43
Services/Tool/System/EnumHelper.cs
Normal file
43
Services/Tool/System/EnumHelper.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
/// <summary>
|
||||
/// 枚举帮助类
|
||||
/// </summary>
|
||||
public static class EnumHelper
|
||||
{
|
||||
|
||||
///// <summary>
|
||||
///// 获取枚举的Short类型
|
||||
///// </summary>
|
||||
///// <param name="value"></param>
|
||||
///// <returns></returns>
|
||||
//public static short GetShortValue(Enum value)
|
||||
//{
|
||||
// return short.Parse(((int)Enum.Parse(value.GetType(), value.ToString())).ToString());
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 得到枚举中文备注
|
||||
///// </summary>
|
||||
///// <param name="enumValue"></param>
|
||||
///// <returns></returns>
|
||||
//public static string GetEnumDesc(Enum enumValue)
|
||||
//{
|
||||
// string value = enumValue.ToString();
|
||||
// FieldInfo field = enumValue.GetType().GetField(value);
|
||||
// object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
|
||||
// if (objs.Length == 0) //当描述属性没有时,直接返回名称
|
||||
// return value;
|
||||
// DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
|
||||
// return descriptionAttribute.Description;
|
||||
//}
|
||||
}
|
||||
}
|
||||
86
Services/Tool/System/IPHelper.cs
Normal file
86
Services/Tool/System/IPHelper.cs
Normal file
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
public class IPHelper
|
||||
{
|
||||
public static string GetIP()
|
||||
{
|
||||
if (HttpContext.Current == null)
|
||||
{
|
||||
throw new Exception("HttpContext.Current为null");
|
||||
}
|
||||
string ip = string.Empty;
|
||||
if (!string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
|
||||
ip = Convert.ToString(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
|
||||
if (string.IsNullOrEmpty(ip))
|
||||
ip = Convert.ToString(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
|
||||
return ip;
|
||||
}
|
||||
|
||||
/// <summary>获取客户端的IP,可以取到代理后的IP
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetClientIp()
|
||||
{
|
||||
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
|
||||
if (!string.IsNullOrEmpty(result))
|
||||
{
|
||||
//可能有代理
|
||||
if (result.IndexOf(".", StringComparison.Ordinal) == -1)
|
||||
result = null;
|
||||
else
|
||||
{
|
||||
if (result.IndexOf(",", StringComparison.Ordinal) != -1)
|
||||
{
|
||||
//有“,”,估计多个代理。取第一个不是内网的IP。
|
||||
result = result.Replace(" ", "").Replace("'", "");
|
||||
string[] temparyip = result.Split(",;".ToCharArray());
|
||||
foreach (string t in temparyip)
|
||||
{
|
||||
if (IsIpAddress(t)
|
||||
&& t.Substring(0, 3) != "10."
|
||||
&& t.Substring(0, 7) != "192.168"
|
||||
&& t.Substring(0, 7) != "172.16.")
|
||||
{
|
||||
return t; //找到不是内网的地址
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (IsIpAddress(result)) //代理即是IP格式
|
||||
return result;
|
||||
else
|
||||
result = null; //代理中的内容 非IP,取IP
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrEmpty(result))
|
||||
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
|
||||
if (string.IsNullOrEmpty(result))
|
||||
result = HttpContext.Current.Request.UserHostAddress;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>判断是否是IP地址格式 0.0.0.0
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="str">待判断的IP地址</param>
|
||||
/// <returns>true or false</returns>
|
||||
public static bool IsIpAddress(string str)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str) || str.Length < 7 || str.Length > 15) return false;
|
||||
|
||||
const string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$";
|
||||
|
||||
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
|
||||
return regex.IsMatch(str);
|
||||
}
|
||||
}
|
||||
}
|
||||
1194
Services/Tool/System/StringHelp.cs
Normal file
1194
Services/Tool/System/StringHelp.cs
Normal file
File diff suppressed because it is too large
Load Diff
72
Services/Tool/TokenHelper.cs
Normal file
72
Services/Tool/TokenHelper.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using JWT;
|
||||
using JWT.Algorithms;
|
||||
using JWT.Serializers;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Services.Tool
|
||||
{
|
||||
/// <summary>
|
||||
/// Token辅助类
|
||||
/// 需要引用jwt包
|
||||
/// </summary>
|
||||
public class TokenHelper
|
||||
{
|
||||
//私钥
|
||||
static string Private_key = "CWLCJLWQZYY";
|
||||
//创建一个世界协调时间提供对象 utc时间协调时间
|
||||
static IDateTimeProvider provider = new UtcDateTimeProvider();
|
||||
//时间戳起点时间
|
||||
static DateTime timeEpoch = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
|
||||
//序列化对象
|
||||
static IJsonSerializer serializer = new JsonNetSerializer();
|
||||
//编码序列化对象
|
||||
static IBase64UrlEncoder encoder = new JwtBase64UrlEncoder();
|
||||
//编码算法
|
||||
static IJwtAlgorithm algorithm = new HMACSHA384Algorithm();
|
||||
//jwt编码
|
||||
static JwtEncoder jwtEncoder= new JwtEncoder(algorithm,serializer,encoder);
|
||||
//验证对象
|
||||
static IJwtValidator validator = new JwtValidator(serializer,provider);
|
||||
//jwt解码
|
||||
static JwtDecoder decoder = new JwtDecoder(serializer, validator, encoder, algorithm);
|
||||
/// <summary>
|
||||
/// 加密的数据键值对传入
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetToken(Dictionary<string,object> keys,float day)
|
||||
{
|
||||
//荷载,负载,最重要的信息,token中保存的信息 keys
|
||||
var now = provider.GetNow();
|
||||
//获取当前时间距离时间戳的差秒
|
||||
var epochSecons = Math.Round((now-timeEpoch).TotalSeconds);
|
||||
keys.Add("exp",(epochSecons+3600)*24*day);//设置过期时间
|
||||
//jwt同一加密
|
||||
var token = jwtEncoder.Encode(keys,Private_key);
|
||||
return token;
|
||||
}
|
||||
public static string CheckToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
//解码 tonken 私钥 验证是否过期
|
||||
//过期时间验证 系统默认起始时间为1970,1,1,0,0,0 如果验证过期需要保证起始时间一致
|
||||
//要么手动验证过期,现在时间与起始时间的差值如果大于设置exp则过期
|
||||
return JsonConvert.DeserializeObject<Datainfo>(decoder.Decode(token, Private_key,verify: true)).data.ToString();//str数据转成Dictionary<string,object>类型即可
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
public class Datainfo {
|
||||
public dynamic data { get; set; }
|
||||
public dynamic exp { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user