core-build

This commit is contained in:
tongfei
2023-10-18 10:21:21 +08:00
parent 62732ef708
commit 9b739e2e37
33 changed files with 3506 additions and 7 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login
{
public class AccessTokenDto
{
/// <summary>
/// 授权token -- 给前端用的验证token
/// </summary>
public string Token { get; set; }
/// <summary>
/// 授权token -- 单点给过来的token
/// </summary>
public string PhpToken { get; set; }
/// <summary>
/// token头标识
/// </summary>
public string TokenType { get; set; } = "Bearer";
/// <summary>
/// 刷新token
/// </summary>
public string RefreshToken { get; set; }
/// <summary>
/// 过期时间
/// </summary>
public DateTime Expired { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login
{
public class DeptInfoDto
{
public int Id { get; set; }
public string DeptCode { get; set; }
public string DeptName { get; set; }
public int? ManagerId { get; set; }
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login
{
/// <summary>
/// 登录后要保存的信息
/// </summary>
public class LoginInDto
{
public bool SignedIn { get; set; }
/// <summary>
/// 用户信息
/// </summary>
public UserInfoDto UserInfo { get; set; }
/// <summary>
/// token信息
/// </summary>
public AccessTokenDto TokenInfo { get; set; }
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login
{
/// <summary>
/// 登出的dto
/// </summary>
public class LoginOutDto
{
/// <summary>
/// 授权token
/// </summary>
public string Authorization { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public string UcId { get; set; }
/// <summary>
/// PHP-session-ID
/// </summary>
public string SessionId { get; set; }
/// <summary>
/// PHP登录返回的token
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// PHP登录的过期时间
/// </summary>
public DateTime ExpiresIn { get; set; }
/// <summary>
///ops自己产生的token 给前端验证用的
/// </summary>
public string Token { get; set; }
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login
{
/// <summary>
/// 登录后:请求相关全部信息对象
/// </summary>
public class LoginSingleRequest
{
/// <summary>
/// 用户ID
/// </summary>
public int UserId { get; set; }
/// <summary>
/// 供应商
/// </summary>
public int SupplierId { get; set; }
/// <summary>
/// 客户
/// </summary>
public int CustomerId { get; set; }
}
}

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Text;
using WMS.Web.Core.Dto.SingleData;
namespace WMS.Web.Core.Dto.Login
{
/// <summary>
/// 登录后:响应相关全部信息对象
/// </summary>
public class LoginSingleResponse
{
/// <summary>
/// 人员
/// </summary>
public SingleDataResponse Staff { get; set; }
/// <summary>
/// 公司
/// </summary>
public SingleDataResponse Company { get; set; }
/// <summary>
/// 供应商
/// </summary>
public SingleDataResponse Supplier { get; set; }
/// <summary>
/// 客户
/// </summary>
public SingleDataResponse Customer { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login.Temp
{
/// <summary>
/// 部门
/// </summary>
public class LoginJsonDeptTempDto
{
public int id { get; set; }
public string dept_code { get; set; }
public string dept_name { get; set; }
public int? manager { get; set; }
}
}

View File

@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login.Temp
{
/// <summary>
/// 基本信息人员--和单点系统的字段一一对应
/// </summary>
public class LoginJsonTokenTempDto
{
/// <summary>
/// 用户在单点中维一ID
/// </summary>
public int uc_id { get; set; }
/// <summary>
/// 用户编码
/// </summary>
public string staff_code { get; set; }
/// <summary>
/// 用户业务员编码
/// </summary>
public string business_code { get; set; }
/// <summary>
/// 角色id
/// </summary>
public string role_id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string nickname { get; set; }
/// <summary>
/// 头像
/// </summary>
public string avatar { get; set; }
/// <summary>
/// 用户手机
/// </summary>
public string mobile { get; set; }
/// <summary>
/// 用户邮件
/// </summary>
public string email { get; set; }
/// <summary>
/// 公司id
/// </summary>
public int? company_id { get; set; }
/// <summary>
/// 组织id
/// </summary>
public int? org_id { get; set; }
/// <summary>
/// 供应商id
/// </summary>
public int? supplier_id { get; set; }
/// <summary>
/// 客户id
/// </summary>
public int? customer_id { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public string created_at { get; set; }
/// <summary>
/// 更新时间
/// </summary>
public string updated_at { get; set; }
/// <summary>
/// 签名(登录)时间
/// </summary>
public string signin_at { get; set; }
/// <summary>
/// 签名(登录ip
/// </summary>
public string signin_ip { get; set; }
/// <summary>
/// 关闭状态0为未关闭
/// </summary>
public string closed { get; set; }
/// <summary>
/// 用户类型 1为员工2为供应商3为客户
/// </summary>
public int? identity { get; set; }
/// <summary>
/// 部门
/// </summary>
public List<LoginJsonDeptTempDto> depts { get; set; }
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login.Temp
{
/// <summary>
/// 登录后获取的:token 信息-和单点系统的字段一一对应
/// </summary>
public class LoginTempDto
{
/// <summary>
/// 用户在单点中维一ID
/// </summary>
public int uc_id { get; set; }
/// <summary>
/// 单点访问的session id
/// </summary>
public string uc_sessid { get; set; }
/// <summary>
/// 后续与单点通信验证token
/// </summary>
public string access_token { get; set; }
/// <summary>
///access token过期时间
/// </summary>
public int expires_in { get; set; }
/// <summary>
/// 用于access_token过期后刷新用
/// </summary>
public string refresh_token { get; set; }
/// <summary>
/// 加密后的用户数据
/// </summary>
public string encryptedData { get; set; }
}
}

View File

@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.Login
{
public class UserInfoDto
{
public string SeesionId { get; set; }
public int UcId { get; set; }
public List<DeptInfoDto> Depts { get; set; }
/// <summary>
/// 人员ID
/// </summary>
public int StaffId { get; set; }
/// <summary>
/// 用户编码
/// </summary>
public string staff_code { get; set; }
/// <summary>
/// 用户业务员编码
/// </summary>
public string business_code { get; set; }
/// <summary>
/// 头像
/// </summary>
public string Avatar { get; set; }
public int Closed { get; set; }
public string CreatedAt { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Nickname { get; set; }
public string RoleId { get; set; }
public string SigninAt { get; set; }
public string UpdatedAt { get; set; }
/// <summary>
/// 公司id
/// </summary>
public int CompanyId { get; set; }
/// <summary>
/// 公司名称
/// </summary>
public string CompanyName { get; set; }
//org_id, supplier_id ,customer_id, identity: 1为员工2为供应商3为客户
/// <summary>
/// 组织id 用户类型为内部员工的时候才有值
/// </summary>
public int? OrgId { get; set; }
/// <summary>
/// 供应商id 用户类型为供应商的时候才有值
/// </summary>
public int? SupplierId { get; set; }
/// <summary>
/// 供应商名称
/// </summary>
public string SupplierName { get; set; }
/// <summary>
/// 客户id 用户类型为客户的时候才有值
/// </summary>
public int? CustomerId { get; set; }
/// <summary>
/// 客户名称
/// </summary>
public string CustomerName { get; set; }
/// <summary>
/// 用户类型1为员工2为供应商3为客户
/// </summary>
public int? Identity { get; set; }
//public string AuthList { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.SingleData
{
/// <summary>
/// 单点数据-请求统一对象
/// </summary>
public class SingleDataRequest
{
public SingleDataRequest() { }
public SingleDataRequest(int companyId)
{
this.CompanyId = companyId;
}
/// <summary>
/// 公司ID
/// </summary>
public int CompanyId { get; set; }
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Dto.SingleData
{
/// <summary>
/// 单点数据响应-统一对象
/// </summary>
public class SingleDataResponse
{
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 编码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 数值
/// </summary>
public decimal Number { get; set; }
/// <summary>
/// 是否禁用true为禁用false为启用
/// </summary>
public bool Disable { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core
{
/// <summary>
/// 基类
/// </summary>
[Serializable]
public class EntityBase
{
/// <summary>
/// Id
/// </summary>
public virtual int Id { get; set; }
}
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace WMS.Web.Core
{
public class EnumRemarkAttribute : Attribute
{
public string Remark { get; set; }
public EnumRemarkAttribute(string remark)
{
this.Remark = remark;
}
}
public static class EnumOperate
{
public static string GetRemark(this Enum enumInfo)
{
if (enumInfo == null) return "";
Type type = enumInfo.GetType();
//获取字段信息
FieldInfo field = type.GetField(enumInfo.ToString());
if (field == null) return "";
//检查字段是否含有指定特性
if (field.IsDefined(typeof(EnumRemarkAttribute), true))
{
//获取字段上的自定义特性
EnumRemarkAttribute remarkAttribute = (EnumRemarkAttribute)field.GetCustomAttribute(typeof(EnumRemarkAttribute));
return remarkAttribute.Remark;
}
else
{
return enumInfo.ToString();
}
}
}
public class PropertyRemarkAttribute : Attribute
{
public string Remark { get; set; }
public PropertyRemarkAttribute(string remark)
{
this.Remark = remark;
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Exceptions
{
public class WebHttpException : Exception
{
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
public WebHttpException()
{
}
public WebHttpException(string errorCode, string errorMessage)
{
ErrorCode = errorCode;
ErrorMessage = errorMessage;
}
}
}

View File

@@ -0,0 +1,72 @@
using Microsoft.International.Converters.PinYinConverter;
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Help
{
/// <summary>
/// 汉字首字母提取
/// </summary>
public static class CNSpellTranslator
{
public static string GetFirstCode(string name)
{
string result = string.Empty;
foreach (char item in name)
{
try
{
ChineseChar cc = new ChineseChar(item);
if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0)
{
string temp = cc.Pinyins[0].ToString();
// result += temp.Substring(0, temp.Length - 1);
result += temp.Substring(0, 1);//取首字母
}
}
catch (Exception)
{
result += item.ToString();
}
}
return result;
}
/// <summary>
/// 汉字转首字母大写
/// </summary>
/// <param name="strChinese"></param>
/// <returns></returns>
public static string GetFirstSpell(string strChinese)
{
try
{
if (strChinese.Length != 0)
{
StringBuilder fullSpell = new StringBuilder();
for (int i = 0; i < strChinese.Length; i++)
{
var chr = strChinese[i];
fullSpell.Append(GetSpell(chr)[0]);
}
return fullSpell.ToString().ToUpper();//转小写方法为 .ToLower()
}
}
catch (Exception e)
{
return "";
}
return string.Empty;
}
private static string GetSpell(char chr)
{
var coverchr = NPinyin.Pinyin.GetPinyin(chr);
return coverchr;
}
}
}

View File

@@ -0,0 +1,50 @@
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Help
{
public class CacheHelp
{
/// <summary>
/// 定义cache
/// </summary>
private static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
/// <summary>
/// 设置cache
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
public static void SetCacheValue(string key, object value)
{
if (key != null)
{
cache.Set(key, value, new MemoryCacheEntryOptions
{
//SlidingExpiration = TimeSpan.FromSeconds(10)
});
}
}
/// <summary>
/// 获取cache
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static object GetCacheValue(string key)
{
object val = null;
if (key != null && cache.TryGetValue(key, out val))
{
return val;
}
else
{
return default(object);
}
}
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace WMS.Web.Core.Help
{
[Serializable]
public static class ClassClone
{
public static void CopyPropertiesToD<D>(this object s, D d)
{
try
{
var Types = s.GetType();//获得类型
var Typed = d.GetType();
foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段
{
foreach (PropertyInfo dp in Typed.GetProperties())
{
if (dp.Name == sp.Name)//判断属性名是否相同
{
dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性
}
}
}
}
catch (Exception e)
{
throw e;
}
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace WMS.Web.Core.Help
{
[Serializable]
public static class ClassCopyUtil
{
/// <summary>
/// 深度copy
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static T Clone<T>(this T t) where T : class
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The class type must be serializable.", "source");
}
if (t == null) return null;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
using (memoryStream)
{
formatter.Serialize(memoryStream, t);
memoryStream.Position = 0;
return (T)formatter.Deserialize(memoryStream);
}
}
}
}

View File

@@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Help
{
/// <summary>
/// 时间转换
/// </summary>
public static class DateTimeUtil
{
/// <summary>
/// 时间戳计时开始时间
/// </summary>
private static DateTime timeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// DateTime转换为10位时间戳单位
/// </summary>
/// <param name="dateTime"> DateTime</param>
/// <returns>10位时间戳单位</returns>
public static long DateTimeToTimeStamp(this DateTime dateTime)
{
return (long)(dateTime.ToUniversalTime() - timeStampStartTime).TotalSeconds;
}
/// <summary>
/// DateTime转换为13位时间戳单位毫秒
/// </summary>
/// <param name="dateTime"> DateTime</param>
/// <returns>13位时间戳单位毫秒</returns>
public static long DateTimeToLongTimeStamp(this DateTime dateTime)
{
return (long)(dateTime.ToUniversalTime() - timeStampStartTime).TotalMilliseconds;
}
/// <summary>
/// 10位时间戳单位转换为DateTime
/// </summary>
/// <param name="timeStamp">10位时间戳单位</param>
/// <returns>DateTime</returns>
public static DateTime TimeStampToDateTime(this long timeStamp)
{
return timeStampStartTime.AddSeconds(timeStamp).ToLocalTime();
}
/// <summary>
/// 13位时间戳单位毫秒转换为DateTime
/// </summary>
/// <param name="longTimeStamp">13位时间戳单位毫秒</param>
/// <returns>DateTime</returns>
public static DateTime LongTimeStampToDateTime(this long longTimeStamp)
{
return timeStampStartTime.AddMilliseconds(longTimeStamp).ToLocalTime();
}
/// <summary>
/// 转字符串
/// </summary>
/// <param name="date"></param>
/// <returns>DateTime</returns>
public static string DateToStringDay(this DateTime? date)
{
if (date == null) return "";
try
{
DateTime dt = Convert.ToDateTime(date);
return dt.ToString("yyyy-MM-dd");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 转字符串
/// </summary>
/// <param name="date"></param>
/// <returns>DateTime</returns>
public static string DateToStringSeconds(this DateTime? date)
{
if (date == null) return "";
try
{
DateTime dt = Convert.ToDateTime(date);
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 转字符串
/// </summary>
/// <param name="date"></param>
/// <returns>DateTime</returns>
public static string DateToStringMonth(this DateTime? date)
{
if (date == null) return "";
try
{
DateTime dt = Convert.ToDateTime(date);
return dt.ToString("MM年dd月");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 转字符串
/// </summary>
/// <param name="date"></param>
/// <returns>DateTime</returns>
public static string DateToStringDay(this DateTime date)
{
if (date == null) return "";
try
{
DateTime dt = Convert.ToDateTime(date);
return dt.ToString("yyyy-MM-dd");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 转字符串
/// </summary>
/// <param name="date"></param>
/// <returns>DateTime</returns>
public static string DateToStringSeconds(this DateTime date)
{
if (date == null) return "";
try
{
DateTime dt = Convert.ToDateTime(date);
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 转字符串
/// </summary>
/// <param name="date"></param>
/// <returns>DateTime</returns>
public static string DateToStringMonth(this DateTime date)
{
if (date == null) return "";
try
{
DateTime dt = Convert.ToDateTime(date);
return dt.ToString("MM年dd月");
}
catch (Exception)
{
return "";
}
}
}
}

View File

@@ -0,0 +1,220 @@
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace WMS.Web.Core.Help
{
public class HttpClientHelp
{
private HttpOptions _options;
public HttpClientHelp(IOptions<HttpOptions> options)
{
this._options = options?.Value;
}
public string PostHttp(string url, JsonObject reqData, bool isHaveCookie = false, string cookieValue = "", string appSecret = "")
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HMACSHA1 hmacsha1 = new HMACSHA1();
if (!string.IsNullOrEmpty(appSecret))
{
byte[] secret = Encoding.UTF8.GetBytes(appSecret);
hmacsha1.Key = secret;
}
byte[] dataBuffer = Encoding.UTF8.GetBytes(reqData.ToString());
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
int contentLength = dataBuffer.Length;
string rawHmac = Convert.ToBase64String(hashBytes);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = contentLength;
request.Accept = "application/json; charset=utf-8";
request.Headers.Add("Content-Signature", "HMAC-SHA1 " + rawHmac);
if (isHaveCookie)
{
var cook = new Cookie();
cook.Domain = _options.Url;
cook.Name = "PHPSESSID";
cook.Value = cookieValue;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cook);
}
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception ex)
{
writer = null;
Console.WriteLine("链接单点错误异常:" + ex.ToString());
}
writer.Write(dataBuffer, 0, dataBuffer.Length);
writer.Close();
Stream responseStream;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
}
catch (Exception ex)
{
responseStream = null;
//WriteLog("服务器异常" + ex.Message);
}
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string respData = streamReader.ReadToEnd();
responseStream.Close();
return respData;
}
public string PostHttpNoData(string url, string cookieValue = "")
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json; charset=utf-8";
if (!string.IsNullOrEmpty(cookieValue))
{
var cook = new Cookie();
cook.Domain = _options.Url;
cook.Name = "PHPSESSID";
cook.Value = cookieValue;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cook);
}
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception ex)
{
writer = null;
Console.WriteLine("链接单点错误异常:" + ex.ToString());
}
writer.Close();
Stream responseStream;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
}
catch (Exception ex)
{
responseStream = null;
//WriteLog("服务器异常" + ex.Message);
}
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string respData = streamReader.ReadToEnd();
responseStream.Close();
return respData;
}
public string GetHttp(string url, bool isHaveCookie = false, string cookieValue = "")
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HMACSHA1 hmacsha1 = new HMACSHA1();
request.Method = "Get";
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json; charset=utf-8";
if (isHaveCookie)
{
var cook = new Cookie();
cook.Domain = _options.Url;
cook.Name = "PHPSESSID";
cook.Value = cookieValue;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cook);
}
Stream writer;
try
{
writer = request.GetRequestStream();
}
catch (Exception)
{
writer = null;
//WriteLog("连接服务器异常");
}
Stream responseStream;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
}
catch (Exception ex)
{
responseStream = null;
//WriteLog("服务器异常" + ex.Message);
}
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string respData = streamReader.ReadToEnd();
responseStream.Close();
return respData;
}
private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
public async Task<JsonValue> Post(string url, string param, string token)
{
HttpClient _client = new HttpClient();
//读取返回消息
string res = string.Empty;
try
{
//填充formData
if (param == null) param = "";
HttpContent hc = new StringContent(param, Encoding.UTF8)
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/json")//application/x-www-form-urlencoded
}
};
_client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var responseMessage = _client.PostAsync(url, hc).Result;
var msg = await responseMessage.Content.ReadAsStringAsync();
if (msg.Equals(""))
return null;
else
return JsonObject.Parse(msg);
}
catch (Exception ex)
{
}
return null;
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Help
{
public class HttpOptions
{
public string Url { get; set; }
public string K3Url { get; set; }
public string K3UrlLogin { get; set; }
public bool K3Enable { get; set; } = false;
public string EspUrl { get; set; }
public string EspAppId { get; set; }
public string EspAppSecret { get; set; }
}
}

View File

@@ -0,0 +1,119 @@
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Help
{
public class RedisClient
{
private static readonly object Locker = new object();
private ConnectionMultiplexer redisMultiplexer;
IDatabase db = null;
private static RedisClient _redisClient = null;
public static RedisClient redisClient
{
get
{
if (_redisClient == null)
{
lock (Locker)
{
if (_redisClient == null)
{
_redisClient = new RedisClient();
}
}
}
return _redisClient;
}
}
public void InitConnect(string RedisConnection)
{
try
{
redisMultiplexer = ConnectionMultiplexer.Connect(RedisConnection);
db = redisMultiplexer.GetDatabase();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
redisMultiplexer = null;
db = null;
}
}
public RedisClient()
{
}
#region String
/// <summary>
/// 保存单个key value
/// </summary>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
return db.StringSet(key, value, expiry);
}
/// <summary>
/// 获取单个key的值
/// </summary>
public RedisValue GetStringKey(string key)
{
return db.StringGet(key);
}
/// <summary>
/// 移除redis
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool RemoveStringKey(string key)
{
return db.KeyDelete(key);
}
/// <summary>
/// 获取一个key的对象
/// </summary>
public T GetStringKey<T>(string key)
{
if (db == null)
{
return default;
}
var value = db.StringGet(key);
if (value.IsNullOrEmpty)
{
return default;
}
return JsonConvert.DeserializeObject<T>(value);
}
/// <summary>
/// 保存一个对象
/// </summary>
/// <param name="obj"></param>
public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
if (db == null)
{
return false;
}
string json = JsonConvert.SerializeObject(obj);
return db.StringSet(key, json, expiry);
}
#endregion
}
}

View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace WMS.Web.Core.Help
{
public class ValidResult
{
public List<ErrorMember> ErrorMembers { get; set; }
public bool IsVaild { get; set; }
public string GetMessage()
{
string msg = "";
for (int i = 0; i < ErrorMembers.Count(); i++)
{
if (i == 0)
msg = ErrorMembers[i].ErrorMessage;
else
msg += "\r\n" + ErrorMembers[i].ErrorMessage;
}
return msg;
}
}
public class ErrorMember
{
public string ErrorMessage { get; set; }
public string ErrorMemberName { get; set; }
}
public static class ValidatetionHelper
{
public static ValidResult IsValid(object value)
{
ValidResult result = new ValidResult();
try
{
var validationContext = new ValidationContext(value);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(value, validationContext, results, true);
if (!isValid)
{
result.IsVaild = false;
result.ErrorMembers = new List<ErrorMember>();
foreach (var item in results)
{
result.ErrorMembers.Add(new ErrorMember()
{
ErrorMessage = item.ErrorMessage,
ErrorMemberName = item.MemberNames.FirstOrDefault()
});
}
}
else
{
result.IsVaild = true;
}
}
catch (Exception ex)
{
result.IsVaild = false;
result.ErrorMembers = new List<ErrorMember>();
result.ErrorMembers.Add(new ErrorMember()
{
ErrorMessage = ex.Message,
ErrorMemberName = "Internal error"
});
}
return result;
}
}
}

View File

@@ -0,0 +1,184 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace WMS.Web.Core.Internal.Results
{
/// <summary>
/// 结果对象
/// </summary>
public class Result
{
/// <summary>
/// 返回结果对象
/// </summary>
public Result()
{
}
/// <summary>
/// 返回结果对象
/// </summary>
/// <param name="message"></param>
/// <param name="status"></param>
public Result(string message, int status)
{
Status = status;
Message = message;
}
/// <summary>
/// 返回结果对象
/// </summary>
/// <param name="result"></param>
public Result(ValueTuple<int, string> result)
{
Status = result.Item1;
Message = result.Item2;
}
/// <summary>
/// 执行是否成功
/// </summary>
[JsonIgnore]
public bool Success => Status == 200;
/// <summary>
/// 执行是否成功
/// </summary>
[JsonProperty(PropertyName = "isSuccess")]
public bool IsSuccess => Status == 200;
/// <summary>
/// 业务返回码
/// </summary>
[JsonProperty(PropertyName = "status")]
public int Status { get; set; }
/// <summary>
/// 执行返回消息
/// </summary>
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
/// <summary>
/// 转换实体
/// </summary>
/// <param name="result"></param>
protected void To(Result result)
{
Status = result.Status;
Message = result.Message;
}
/// <summary>
/// 转换实体
/// </summary>
/// <param name="message"></param>
/// <param name="status"></param>
protected void To(string message, int status)
{
Status = status;
Message = message;
}
/// <summary>
/// 转换实体
/// </summary>
/// <param name="result">结果对象</param>
protected void To(ValueTuple<int, string> result)
{
Status = result.Item1;
Message = result.Item2;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="message">结果消息</param>
/// <param name="status">结果状态</param>
/// <returns></returns>
public static Result ReFailure(string message, int status)
{
return new Result(message, status);
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果消息</param>
/// <returns></returns>
public static Result ReFailure(ValueTuple<int, string> result)
{
return new Result(result.Item2, result.Item1);
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果</param>
/// <returns></returns>
public static T ReFailure<T>(Result result) where T : Result, new()
{
var r = new T();
r.To(result);
return r;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="message">结果消息</param>
/// <param name="status">结果状态</param>
/// <returns></returns>
public static T ReFailure<T>(string message, int status) where T : Result, new()
{
var result = new T();
result.To(message, status);
return result;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果消息</param>
/// <returns></returns>
public static T ReFailure<T>(ValueTuple<int, string> result) where T : Result, new()
{
var ret = new T();
ret.To(result);
return ret;
}
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <returns></returns>
public static Result ReSuccess()
{
return new Result(BaseResultCodes.Success);
}
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <returns></returns>
public static T ReSuccess<T>() where T : Result, new()
{
var result = new T();
result.To(BaseResultCodes.Success);
return result;
}
/// <summary>
/// 转换为 task
/// </summary>
/// <returns></returns>
public Task<Result> AsTask()
{
return Task.FromResult(this);
}
}
}

View File

@@ -0,0 +1,102 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace WMS.Web.Core.Internal.Results
{
/// <summary>
/// 实体结果对象
/// </summary>
/// <typeparam name="T"></typeparam>
public class Result<T> : Result
{
/// <summary>
/// 实体结果
/// </summary>
public Result()
{
}
/// <summary>
/// 实体结果
/// </summary>
/// <param name="data"></param>
public Result(T data) : base(BaseResultCodes.Success)
{
Data = data;
}
/// <summary>
/// 返回结果对象
/// </summary>
/// <param name="data"></param>
/// <param name="result"></param>
public Result(T data, ValueTuple<int, string> result) : base(result)
{
Data = data;
}
/// <summary>
/// 返回对象
/// </summary>
[JsonProperty(PropertyName = "data")]
public T Data { get; set; }
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <returns></returns>
public static Result<T> ReSuccess(T data)
{
return new Result<T>(data);
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="message">结果消息</param>
/// <param name="status">结果状态</param>
/// <returns></returns>
public new static Result<T> ReFailure(string message, int status)
{
var result = new Result<T>();
result.To(message, status);
return result;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果消息</param>
/// <returns></returns>
public new static Result<T> ReFailure(ValueTuple<int, string> result)
{
var res = new Result<T>();
res.To(result);
return res;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果</param>
/// <returns></returns>
public static Result<T> ReFailure(Result result)
{
var re = new Result<T>();
re.To(result);
return re;
}
/// <summary>
/// 转换为task
/// </summary>
/// <returns></returns>
public new Task<Result<T>> AsTask()
{
return Task.FromResult(this);
}
}
}

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core.Internal.Results
{
public class BaseResultCodes
{
/// <summary>
/// 处理成功
/// </summary>
public static ValueTuple<int, string> Success = (200, "Success");
/// <summary>
/// 错误请求
/// </summary>
public static ValueTuple<int, string> BadRequest = (400, "{0}");
/// <summary>
/// 未授权
/// </summary>
public static ValueTuple<int, string> UnAuthorized = (401, "登录信息已过期,请重新登录");
/// <summary>
/// 拒绝请求
/// </summary>
public static ValueTuple<int, string> NotAcceptable = (403, "Not Acceptable");
/// <summary>
/// 未找到服务
/// </summary>
public static ValueTuple<int, string> NotFound = (404, "Not Found");
/// <summary>
/// 系统错误
/// </summary>
public static ValueTuple<int, string> UnknowError = (500, "Internal Server Error");
/// <summary>
/// 请求超时
/// </summary>
public static ValueTuple<int, string> RequestTimeout = (408, "Request Timeout");
}
/// <summary>
/// 返回对象扩展
/// </summary>
public static class BaseResultCodesExtension
{
/// <summary>
/// 根据替换符进行替换支付
/// </summary>
/// <param name="result">结果对象</param>
/// <param name="args">替换字符</param>
/// <returns></returns>
public static ValueTuple<int, string> ToFormat(this ValueTuple<int, string> result, params string[] args)
{
result.Item2 = string.Format(result.Item2, args);
return result;
}
}
}

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace WMS.Web.Core.Internal.Results
{
/// <summary>
/// 集合结果类
/// </summary>
/// <typeparam name="T"></typeparam>
public class ResultList<T> : Result<IList<T>>
{
/// <summary>
/// 实体集合结果
/// </summary>
public ResultList()
{
}
/// <summary>
/// 实体集合结果
/// </summary>
/// <param name="data">实体集合</param>
public ResultList(IList<T> data) : base(data)
{
}
/// <summary>
/// 实体集合结果
/// </summary>
/// <param name="data">实体集合</param>
/// <param name="result">结果状态</param>
public ResultList(IList<T> data, ValueTuple<int, string> result) : base(data, result)
{
}
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <returns></returns>
public new static ResultList<T> ReSuccess(IList<T> data)
{
return new ResultList<T>(data);
}
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <returns></returns>
public new static ResultList<T> ReSuccess()
{
return new ResultList<T>(new List<T>());
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="message">结果消息</param>
/// <param name="status">结果状态</param>
/// <returns></returns>
public new static ResultList<T> ReFailure(string message, int status)
{
var result = new ResultList<T>();
result.To(message, status);
return result;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果消息</param>
/// <returns></returns>
public new static ResultList<T> ReFailure(ValueTuple<int, string> result)
{
var res = new ResultList<T>();
res.To(result);
return res;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果</param>
/// <returns></returns>
public new static ResultList<T> ReFailure(Result result)
{
var re = new ResultList<T>();
re.To(result);
return re;
}
/// <summary>
/// 转换为 task
/// </summary>
/// <returns></returns>
public new Task<ResultList<T>> AsTask()
{
return Task.FromResult(this);
}
}
}

View File

@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace WMS.Web.Core.Internal.Results
{
/// <summary>
/// 分页列表结果对象
/// </summary>
public class ResultPagedList<T> : ResultList<T>
{
/// <summary>
/// 实体分页集合结果
/// </summary>
public ResultPagedList()
{
}
/// <summary>
/// 实体分页集合结果
/// </summary>
/// <param name="data">实体集合</param>
/// <param name="totalCount">总条数</param>
public ResultPagedList(IList<T> data, int totalCount) : base(data)
{
TotalCount = totalCount;
}
/// <summary>
/// 实体分页集合结果
/// </summary>
/// <param name="data"></param>
/// <param name="totalCount"></param>
/// <param name="result"></param>
public ResultPagedList(IList<T> data, int totalCount, ValueTuple<int, string> result) : base(data, result)
{
TotalCount = totalCount;
}
/// <summary>
/// Total count of Items.
/// </summary>
public int TotalCount { get; set; }
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <param name="data">实体集合</param>
/// <param name="totalCount">总条数</param>
/// <returns></returns>
public static ResultPagedList<T> ReSuccess(IList<T> data, int totalCount)
{
return new ResultPagedList<T>(data, totalCount);
}
/// <summary>
/// 创建成功的返回消息
/// </summary>
/// <returns></returns>
public new static ResultPagedList<T> ReSuccess()
{
return new ResultPagedList<T>(new List<T>(), 0);
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="message">结果消息</param>
/// <param name="status">结果状态</param>
/// <returns></returns>
public new static ResultPagedList<T> ReFailure(string message, int status)
{
var result = new ResultPagedList<T>();
result.To(message, status);
return result;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果消息</param>
/// <returns></returns>
public new static ResultPagedList<T> ReFailure(ValueTuple<int, string> result)
{
var res = new ResultPagedList<T>();
res.To(result);
return res;
}
/// <summary>
/// 创建返回信息(返回处理失败)
/// </summary>
/// <param name="result">结果</param>
/// <returns></returns>
public new static ResultPagedList<T> ReFailure(Result result)
{
var re = new ResultPagedList<T>();
re.To(result);
return re;
}
/// <summary>
/// 转换为 task
/// </summary>
/// <returns></returns>
public new Task<ResultPagedList<T>> AsTask()
{
return Task.FromResult(this);
}
}
}

View File

@@ -0,0 +1,463 @@
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace WMS.Web.Core.Internal.Security
{
public class RSA
{
#region 使
//encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
private static byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
private static byte[] Seq = new byte[15];
/// <summary>
/// 用于签名的私钥
/// </summary>
public static RsaSecurityKey RSAPrivateKey { get; }
/// <summary>
/// 用于验证的公钥
/// </summary>
public static RsaSecurityKey RSAPublicKey { get; }
static RSA()
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
RSAPrivateKey = new RsaSecurityKey(rsa.ExportParameters(true));
RSAPublicKey = new RsaSecurityKey(rsa.ExportParameters(false));
rsa.PersistKeyInCsp = false;
}
}
/// <summary>
/// 签名
/// </summary>
/// <param name="content">签名内容</param>
/// <param name="privateKey">私钥</param>
/// <param name="encoding">编码类型</param>
/// <param name="hashAlgorithm">加密方式</param>
/// <returns>加密密文</returns>
public static string Sign(string content, string privateKey, Encoding encoding, HashAlgorithmName hashAlgorithm)
{
var rsa = System.Security.Cryptography.RSA.Create();
rsa.ImportParameters(DecodePkcsPrivateKey(privateKey));
var contentBytes = encoding.GetBytes(content);
var cipherBytes = rsa.SignData(contentBytes, hashAlgorithm, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(cipherBytes);
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="content">验证签名内容</param>
/// <param name="publicKey">公钥</param>
/// <param name="sign">签名密文</param>
/// <param name="encoding">编码类型</param>
/// <param name="hashAlgorithm">加密方式</param>
/// <returns>加密密文</returns>
public static bool CheckSign(string content, string publicKey, string sign, Encoding encoding, HashAlgorithmName hashAlgorithm)
{
var rsa = System.Security.Cryptography.RSA.Create();
rsa.ImportParameters(DecodePkcsPublicKey(publicKey));
var contentBytes = encoding.GetBytes(content);
var signBytes = Convert.FromBase64String(sign);
return rsa.VerifyData(contentBytes, signBytes, hashAlgorithm, RSASignaturePadding.Pkcs1);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="cipher">密文</param>
/// <param name="privateKey">私钥</param>
/// <param name="encoding">编码</param>
/// <returns>明文</returns>
public static string Decrypt(string cipher, string privateKey, Encoding encoding)
{
var rsa = System.Security.Cryptography.RSA.Create();
rsa.ImportParameters(DecodePkcsPrivateKey(privateKey));
var cipherBytes = System.Convert.FromBase64String(cipher);
var plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
return encoding.GetString(plainTextBytes);
}
public static System.Security.Cryptography.RSA CreateRSA(string privatekey)
{
var rsa = System.Security.Cryptography.RSA.Create();
rsa.ImportParameters(DecodePkcsPrivateKey(privatekey));
return rsa;
}
public static string DecryptToDo(System.Security.Cryptography.RSA rsa, string cipher, Encoding encoding)
{
var cipherBytes = System.Convert.FromBase64String(cipher);
var plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
return encoding.GetString(plainTextBytes);
}
/// <summary>
/// 加密
/// </summary>
/// <param name="plainText ">明文</param>
/// <param name="publicKey">公钥</param>
/// <param name="encoding">编码</param>
/// <returns>密文</returns>
public static string Encrypt(string plainText, string publicKey, Encoding encoding)
{
var rsa = System.Security.Cryptography.RSA.Create();
rsa.ImportParameters(DecodePkcsPublicKey(publicKey));
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
var cipherBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(cipherBytes);
}
/// <summary>
/// 解密公钥
/// </summary>
/// <param name="publicKey"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public static RSAParameters DecodePkcsPublicKey(string publicKey)
{
if (string.IsNullOrEmpty(publicKey))
throw new ArgumentNullException("publicKey", "This arg cann't be empty.");
publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\n", "").Replace("\r", "");
var publicKeyData = Convert.FromBase64String(publicKey);
//生成RSA参数
var rsaParams = new RSAParameters();
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob -----
using (BinaryReader binr = new BinaryReader(new MemoryStream(publicKeyData)))
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)//data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
Seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(Seq, SeqOID)) //make sure Sequence for OID is correct
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes
else
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;
if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0);
int firstbyte = binr.PeekChar();
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
throw new ArgumentException("PemToXmlPublicKey Conversion failed");
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
rsaParams.Modulus = modulus;
rsaParams.Exponent = exponent;
}
return rsaParams;
}
/// <summary>
/// 私钥解密
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public static RSAParameters DecodePkcsPrivateKey(string privateKey)
{
if (string.IsNullOrEmpty(privateKey))
{
throw new ArgumentNullException("pemFileConent", "This arg cann't be empty.");
}
try
{
privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\n", "").Replace("\r", "");
var privateKeyData = Convert.FromBase64String(privateKey);
//解析Pkcs证书
PKCSType type = GetPrivateKeyType(privateKeyData.Length);
if (type == PKCSType.PKCS_8_1024 || type == PKCSType.PKCS_8_2048)
{
//Pkcs#8秘钥需要特殊处理
privateKeyData = DecodePkcs8PrivateKey(privateKeyData);
}
var rsaParams = new RSAParameters();
byte bt = 0;
ushort twobytes = 0;
//转换为二进制值
using (var binr = new BinaryReader(new MemoryStream(privateKeyData)))
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
throw new ArgumentException("Unexpected value read )");
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102)
throw new ArgumentException("Unexpected version");
bt = binr.ReadByte();
if (bt != 0x00)
throw new ArgumentException("Unexpected value read ");
//转换XML
rsaParams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.D = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.P = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.Q = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.DP = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.DQ = binr.ReadBytes(GetIntegerSize(binr));
rsaParams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
}
return rsaParams;
}
catch (Exception ex)
{
throw new ArgumentException("此私钥证书无效", ex);
}
}
/// <summary>
/// Pkcs#8 证书解密
/// </summary>
/// <param name="privateKeyData"></param>
/// <returns></returns>
private static byte[] DecodePkcs8PrivateKey(byte[] privateKeyData)
{
byte bt = 0;
ushort twobytes = 0;
MemoryStream mem = new MemoryStream(privateKeyData);
int lenstream = (int)mem.Length;
using (var binr = new BinaryReader(mem))
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
throw new Exception("Unexpected value read");
bt = binr.ReadByte();
if (bt != 0x02)
throw new Exception("Unexpected version");
twobytes = binr.ReadUInt16();
if (twobytes != 0x0001)
throw new Exception("Unexpected value read");
Seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(Seq, SeqOID)) //make sure Sequence for OID is correct
throw new Exception("Unexpected value read");
bt = binr.ReadByte();
if (bt != 0x04) //expect an Octet string
throw new Exception("Unexpected value read");
bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
if (bt == 0x81)
binr.ReadByte();
else
if (bt == 0x82)
binr.ReadUInt16();
//------ at this stage, the remaining sequence should be the RSA private key
return binr.ReadBytes((int)(lenstream - mem.Position));
}
}
/// <summary>
/// 获取Integer的大小
/// </summary>
/// <param name="binr"></param>
/// <returns></returns>
private static int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02)
return 0;
bt = binr.ReadByte();
if (bt == 0x81)
count = binr.ReadByte();
else
if (bt == 0x82)
{
highbyte = binr.ReadByte();
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt;
}
while (binr.ReadByte() == 0x00)
{
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current);
return count;
}
private static bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i = 0;
foreach (byte c in a)
{
if (c != b[i])
return false;
i++;
}
return true;
}
/// <summary>
/// 获取私钥的类型
/// </summary>
/// <param name="privateKeyLength"></param>
/// <returns></returns>
private static PKCSType GetPrivateKeyType(int privateKeyLength)
{
if (privateKeyLength >= 630 && privateKeyLength <= 640)
return PKCSType.PKCS_8_1024;
if (privateKeyLength >= 600 && privateKeyLength <= 610)
return PKCSType.PKCS_1_1024;
if (privateKeyLength >= 1210 && privateKeyLength <= 1220)
return PKCSType.PKCS_8_2048;
if (privateKeyLength >= 1190 && privateKeyLength <= 1199)
return PKCSType.PKCS_1_2048;
else
throw new ArgumentException("此私钥证书标准不支持");
}
#endregion
#region 使
/// <summary>
/// php单点登录解析token根据密钥-分段解析
/// </summary>
/// <param name="privateKey"></param>
/// <param name="items"></param>
/// <returns></returns>
public static string DecryptSection(string privateKey, List<string> items)
{
string data = "";
using (var rsa = new RSACryptoServiceProvider())
{
var para = DecodePkcsPrivateKey(privateKey);
rsa.ImportParameters(para);
foreach (var item in items)
{
//var aa= "lhIweHzS3fYrnhM0HmmQIJIm9jsCAOAHEZFYRF+96vsoWRxxEwkmZsjESMIy7UXGQmo1/Q3GIs96ItlJ0LbJWY0tBggS3JHQ9bnfWKIzeFY2aMi9wPqJbWujXzwlAvi0div2YUnn+fj5sGPdYPN0RAwGUbVHpuT/XOSMYfHaGJkt/FcD+ihvx7/GP+sxXbTr/4/NwhSVDd8lmzavu+RaQKOBcYZ4AXNSS1CZ9mQ3Fau+o2eJL6byBqVtAtBdD9bki1yMMNTkOdl0LyUc4T2EtZOdYAa4EenVsFV0W7SBq7yqc/WCEThMEOQfu4t/tiRg8UrySrZmWHD1AUJnzSKvMg==Sl0Fnt+sP0pCivX/F+6/TJfIN9gh9E/CfmgUWEZmWJXURSYXIIjA1T8guUwPnmSt7buMlDAWSKByk6q9Qry1kt6DFJM92uPXyRsgYO3/ZkuDVupt22Jmdk5n075gJ+wbQfr1o05Pc84t0SGo2ZwNdsaynLk/4oZzezSiQTKLUqv3XuDBHo9QGe0dlPAk/g+KzwA3RGTX+r8bJFlhjP2kSpPd6aemeAjKElKqHnXXUem4nq1mK1SvIhejrM8m2uA7oFY+yo00ZLp9ZfD8HT1tqbpdisWbkf22vbB9Y0TPITWgAIAOcv13H6oCQJ+UAHpRmcRUpWYph3LyrU6GW9b6uA==";
//老的处理方式反转byte字节单点返回数据
//var bty = Convert.FromBase64String(item);
//byte[] DecryptByte = rsa.Decrypt(bty, false);
//Array.Reverse(DecryptByte, 0, DecryptByte.Length);
//data += Encoding.UTF8.GetString(DecryptByte,0, DecryptByte.Length);
//新的处理方式,反转字符串(单点返回数据-做了其它统一处理)
var bty = Convert.FromBase64String(item);
byte[] DecryptByte = rsa.Decrypt(bty, false);
var result = Encoding.UTF8.GetString(DecryptByte, 0, DecryptByte.Length);
var chars = result.ToCharArray();
Array.Reverse(chars, 0, chars.Length);
string reverse = String.Empty;
foreach (var chr in chars)
{
reverse += chr;
}
data += reverse;
}
return data;
}
}
#endregion
}
/// <summary>
/// 密钥类型枚举
/// </summary>
public enum PKCSType
{
/// <summary>
/// 1024
/// </summary>
PKCS_1_1024,
/// <summary>
/// 2048
/// </summary>
PKCS_1_2048,
/// <summary>
/// 1023
/// </summary>
PKCS_8_1024,
/// <summary>
/// 2048
/// </summary>
PKCS_8_2048,
}
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace WMS.Web.Core
{
/// <summary>
/// 数值处理
/// </summary>
public static class NumericalProcess
{
/// <summary>
/// Decimal 数值精度转换
/// </summary>
/// <param name="number"> decimal数值</param>
/// <param name="precision">精度值</param>
/// <param name="RoundoffType"> 舍入类型1为进位2为舍位3为四舍五入</param>
/// <returns>decimal数值</returns>
public static decimal DecimalPrecision(this decimal? number, int? precision, int? RoundoffType)
{
if (RoundoffType == 1)
return Decimal.Round(number ?? 0, precision ?? 0, MidpointRounding.ToPositiveInfinity);
else if (RoundoffType == 2)
return Decimal.Round(number ?? 0, precision ?? 0, MidpointRounding.ToZero);
else if (RoundoffType == 3)
return Decimal.Round(number ?? 0, precision ?? 0, MidpointRounding.AwayFromZero);
return number ?? 0;
}
/// <summary>
/// Decimal 数值精度转换
/// </summary>
/// <param name="number"> decimal数值</param>
/// <param name="precision">精度值</param>
/// <param name="RoundoffType"> 舍入类型1为进位2为舍位3为四舍五入</param>
/// <returns>decimal数值</returns>
public static decimal DecimalPrecision(this decimal number, int? precision, int? RoundoffType)
{
if (RoundoffType == 1)
return Decimal.Round(number, precision ?? 0, MidpointRounding.ToPositiveInfinity);
else if (RoundoffType == 2)
return Decimal.Round(number, precision ?? 0, MidpointRounding.ToZero);
else if (RoundoffType == 3)
return Decimal.Round(number, precision ?? 0, MidpointRounding.AwayFromZero);
return number;
}
/// <summary>
/// Decimal 去掉后面无效的0
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string DecimalToStringNoZero(this decimal? data)
{
return (data ?? 0).ToString("#0.##########");
}
public static string DecimalToStringNoZero(this decimal data)
{
return data.ToString("#0.##########");
}
}
}

View File

@@ -10,13 +10,6 @@
<DocumentationFile>../WMS.Web.Api/wwwroot/WMS.Web.Core.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Folder Include="Dto\" />
<Folder Include="Exceptions\" />
<Folder Include="Help\" />
<Folder Include="Internal\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />