提交代码

This commit is contained in:
zpc 2024-06-05 20:28:56 +08:00
commit 3309f030c3
9 changed files with 1447 additions and 0 deletions

400
.gitignore vendored Normal file
View File

@ -0,0 +1,400 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
# **/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.34916.146
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLib.NetCore.Utility", "XLib.NetCore.Utility\XLib.NetCore.Utility.csproj", "{E97848F8-EBAB-4387-ACA9-DBF5F57635AC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BC4E4FC3-F15C-488A-84ED-4EE5D957B1FB}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,97 @@
using System;
namespace XLib.NetCore.Utility
{
/// <summary>
///
/// </summary>
public static class DateTimeUtil
{
/// <summary>
/// 根据本周周几获取当周周一
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static DateTime GetMondayOfThisWeek(this DateTime date)
{
// 获取今天是周几DayOfWeek返回的是一个枚举其中Sunday=0, Monday=1, ..., Saturday=6
int diff = date.DayOfWeek - DayOfWeek.Monday;
// 如果今天是周一或者之前diff小于等于0那么本周一就是今天或者之前的某一天
if (diff <= 0)
{
diff += 7; // 加上一周的天数确保diff是正数
}
// 返回本周一的日期今天的日期减去diff天
return date.AddDays(-diff);
}
/// <summary>
/// 根据本周周几获取当周周日
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static DateTime GetSundayThisWeek(this DateTime date)
{
// 获取当前日期是周几DayOfWeek是枚举其中Sunday的值为0
int dayOfWeek = (int)date.DayOfWeek;
// 计算周日距离今天的天数差
int daysToSunday = (7 - dayOfWeek) % 7;
// 如果今天是周日,则返回出去
if (daysToSunday == 0)
{
return date;
}
// 添加相应的天数得到当周的周日
DateTime sundayThisWeek = date.AddDays(daysToSunday);
return sundayThisWeek;
}
/// <summary>
/// 给时间添加周
/// </summary>
/// <param name="dateTime"></param>
/// <param name="weeksToAdd">周</param>
/// <returns></returns>
public static DateTime AddWeeks(this DateTime dateTime, int weeksToAdd)
{
// 计算要添加的总天数一周为7天
int daysToAdd = weeksToAdd * 7;
// 使用DateTime的AddDays方法添加天数
DateTime resultDate = dateTime.AddDays(daysToAdd);
return resultDate;
}
/// <summary>
///
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long ConvertToUnixTimestamp(this DateTime dateTime)
{
DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime);
return dateTimeOffset.ToUnixTimeSeconds();
}
/// <summary>
///
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long ConvertToUnixTimestampMilliseconds(this DateTime dateTime)
{
DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime);
return dateTimeOffset.ToUnixTimeMilliseconds();
}
}
}

View File

@ -0,0 +1,163 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace XLib.NetCore.Utility
{
/// <summary>
/// FileUtil
/// </summary>
public static class FileUtil
{
// 把byte保存成二进制文件
public static void Byte2file(string file_name, byte[] b, int len)
{
using (FileStream fs = new FileStream(file_name, FileMode.OpenOrCreate))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(b, 0, len);
}
}
}
#region CSV文件
/// <summary>
/// 根据类型写CSV文件第一行
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="filePath">文件路径</param>
/// <param name="append">是否追加</param>
public static void WriteCsvHeaderLine<T>(string filePath, bool append)
{
using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8))
{
// 使用反射获取字段名
PropertyInfo[] properties = typeof(T).GetProperties();
string header = string.Join(",", properties.Select(p => p.Name));
writer.WriteLine(header);
writer.Close();
}
}
/// <summary>
/// 根据类型写CSV文件第一行
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="entity">数据</param>
/// <param name="filePath">文件路径</param>
/// <param name="append">是否追加</param>
public static void AppendCsvFile<T>(T entity, string filePath, bool append)
{
using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8))
{
// 使用反射获取字段名
PropertyInfo[] properties = typeof(T).GetProperties();
string data = string.Join(",", properties.Select(p => p.GetValue(entity)));
writer.WriteLine(data);
writer.Close();
}
}
/// <summary>
/// 根据类型写CSV文件第一行
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="entity">数据</param>
/// <param name="filePath">文件路径</param>
/// <param name="append">是否追加</param>
public static void AppendCsvFile<T>(IEnumerable<T> list, string filePath, bool append)
{
using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8))
{
// 使用反射获取字段名
PropertyInfo[] properties = typeof(T).GetProperties();
// 写入数据
foreach (var entity in list)
{
string data = string.Join(",", properties.Select(p => p.GetValue(entity)));
writer.WriteLine(data);
}
writer.Close();
}
}
/// <summary>
/// 把列表数据写入CSV文件
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="list">列表</param>
/// <param name="filePath">文件路径</param>
/// <param name="append">是否append文件</param>
public static void WriteCsvHeaderFile<T>(IEnumerable<T> list, string filePath, bool append)
{
using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8))
{
// 使用反射获取字段名
PropertyInfo[] properties = typeof(T).GetProperties();
string header = string.Join(",", properties.Select(p => p.Name));
writer.WriteLine(header);
// 写入数据
foreach (var entity in list)
{
string data = string.Join(",", properties.Select(p => p.GetValue(entity)));
writer.WriteLine(data);
}
writer.Close();
}
}
#endregion
/// <summary>
/// 获取硬盘剩余空间,单位字节
/// 如果失败返回0
/// </summary>
/// <returns></returns>
public static long GetDiskSpace(string filePath)
{
string directoryPath = Path.GetFullPath(filePath);
//linux平台需要创建文件夹才能获取到硬盘信息
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
long availableSpace = 0;
DriveInfo driveInfo = new DriveInfo(directoryPath);
if (driveInfo.IsReady)
{
availableSpace = driveInfo.AvailableFreeSpace;
return availableSpace;
}
return availableSpace;
}
/// <summary>
/// 检查文件后缀是否是图片
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool IsImageByExtension(string filePath)
{
string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico" }; // 可以根据需要添加更多扩展名
string extension = Path.GetExtension(filePath).ToLowerInvariant();
return imageExtensions.Contains(extension);
}
}
}

View File

@ -0,0 +1,95 @@
using System;
using System.Diagnostics;
using System.IO;
namespace XLib.NetCore.Utility
{
/// <summary>
/// linux shell 功能
/// </summary>
public class LinuxShellUtil
{
/// <summary>
/// 执行linux shell命令
/// 例子string command = "/usr/bin/systemctl restart sunny-sports.service";
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public static int ExcuteShellCommand(string command)
{
// 创建一个进程对象
Process process = new Process();
// 设置进程启动信息
process.StartInfo.FileName = "/bin/bash"; // 指定要执行的shell
process.StartInfo.Arguments = $"-c \"{command}\""; // 设置命令参数
process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
process.StartInfo.UseShellExecute = false; // 不使用操作系统shell启动进程
process.StartInfo.CreateNoWindow = true; // 不创建窗口
// 启动进程
process.Start();
// 读取进程的输出
string output = process.StandardOutput.ReadToEnd();
// 等待进程执行完毕
process.WaitForExit();
// 输出结果
int exitCode = process.ExitCode;
process.Close();
Console.WriteLine($"脚本执行完毕,退出码:{exitCode}");
return exitCode;
}
/// <summary>
/// 执行脚本
/// 例子: string scriptPath = "./restart_service.sh";
/// </summary>
/// <returns></returns>
public static int ExcuteShellScript(string scriptPath)
{
scriptPath = Path.GetFullPath(scriptPath);
Process process = new Process();
process.StartInfo.FileName = "/bin/bash";
process.StartInfo.Arguments = scriptPath;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
int exitCode = process.ExitCode;
process.Close();
Console.WriteLine($"脚本执行完毕,退出码:{exitCode}");
return exitCode;
}
}
}

View File

@ -0,0 +1,88 @@
namespace XLib.NetCore.Utility
{
using System;
using System.Collections.Concurrent;
using System.Reflection;
/// <summary>
/// 用于缓存反射数据以提高性能。
/// </summary>
public static class ReflectionCache
{
/// <summary>
/// 用于缓存 Type 对象,键是类型名称
/// </summary>
private static readonly ConcurrentDictionary<string, Type> TypeCache = new ConcurrentDictionary<string, Type>();
/// <summary>
/// 用于缓存属性信息数组,键是 Type 对象
/// </summary>
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> PropertyCache = new ConcurrentDictionary<Type, PropertyInfo[]>();
/// <summary>
/// 用于缓存字段信息数组,键是 Type 对象
/// </summary>
private static readonly ConcurrentDictionary<Type, FieldInfo[]> FieldCache = new ConcurrentDictionary<Type, FieldInfo[]>();
/// <summary>
/// 用于缓存方法信息数组,键是 Type 对象
/// </summary>
private static readonly ConcurrentDictionary<Type, MethodInfo[]> MethodCache = new ConcurrentDictionary<Type, MethodInfo[]>();
/// <summary>
/// 用于缓存构造函数信息数组,键是 Type 对象
/// </summary>
private static readonly ConcurrentDictionary<Type, ConstructorInfo[]> ConstructorCache = new ConcurrentDictionary<Type, ConstructorInfo[]>();
/// <summary>
/// 获取指定类型名称的 Type 对象,如果缓存中存在则使用缓存。
/// </summary>
/// <param name="typeName">类型的全名。</param>
/// <returns>指定类型名称的 Type 对象。</returns>
public static Type GetType(string typeName)
{
return TypeCache.GetOrAdd(typeName, t => Type.GetType(t));
}
/// <summary>
/// 获取指定 Type 的属性信息数组,如果缓存中存在则使用缓存。
/// </summary>
/// <param name="type">Type 对象。</param>
/// <returns>指定 Type 的属性信息数组。</returns>
public static PropertyInfo[] GetProperties(Type type)
{
return PropertyCache.GetOrAdd(type, t => t.GetProperties());
}
/// <summary>
/// 获取指定 Type 的字段信息数组,如果缓存中存在则使用缓存。
/// </summary>
/// <param name="type">Type 对象。</param>
/// <returns>指定 Type 的字段信息数组。</returns>
public static FieldInfo[] GetFields(Type type)
{
return FieldCache.GetOrAdd(type, t => t.GetFields());
}
/// <summary>
/// 获取指定 Type 的方法信息数组,如果缓存中存在则使用缓存。
/// </summary>
/// <param name="type">Type 对象。</param>
/// <returns>指定 Type 的方法信息数组。</returns>
public static MethodInfo[] GetMethods(Type type)
{
return MethodCache.GetOrAdd(type, t => t.GetMethods());
}
/// <summary>
/// 获取指定 Type 的构造函数信息数组,如果缓存中存在则使用缓存。
/// </summary>
/// <param name="type">Type 对象。</param>
/// <returns>指定 Type 的构造函数信息数组。</returns>
public static ConstructorInfo[] GetConstructors(Type type)
{
return ConstructorCache.GetOrAdd(type, t => t.GetConstructors());
}
}
}

View File

@ -0,0 +1,448 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace XLib.NetCore.Utility
{
/// <summary>
///
/// </summary>
public static class SecurityUtility
{
/// <summary>
/// 根据文件的二进制内容取得其Hash值用于Smartdownload的时候比较非.NetAssembly文件的版本号。
/// </summary>
/// <param name="filename">文件顽症路径</param>
/// <returns></returns>
public static string GetFileMD5Hash(string filename)
{
if (!File.Exists(filename)) return "";
FileStream fstr = File.OpenRead(filename);
byte[] buff = new byte[fstr.Length];
fstr.Position = 0;
fstr.Read(buff, 0, (int)fstr.Length);
fstr.Close();
//创建 MD5CryptoServiceProvider 实例。
MD5 md5Hasher = MD5.Create();
// 把原始字符串转化成一组byte数组并计算hash值。
byte[] data = md5Hasher.ComputeHash(buff);
//创建string builder
StringBuilder sBuilder = new StringBuilder();
//把hash值的数组16进制后合并成字符串
for (int i = data.Length - 1; i >= 0; i--)
{
sBuilder.Append(data[i].ToString("x2"));
}
//return
return sBuilder.ToString();
}
/// <summary>
/// 计算字符串的 MD5 哈希值,并将该哈希作为 32 字符的十六进制格式字符串返回。
/// </summary>
/// <param name="sourceString">原始字符串.</param>
/// <returns>MD5 hash 后的32位字符串</returns>
/// <remarks>MD5 算法的哈希值大小为 128 位。</remarks>
/// <exception cref="ArgumentNullException">传入的引用参数为null或空字符串。</exception>
/// <history>
/// 2008/12/18 9:19 Created
/// </history>
public static string GetMD5Hash(string sourceString)
{
//创建 MD5CryptoServiceProvider 实例。
MD5 md5Hasher = MD5.Create();
// 把原始字符串转化成一组byte数组并计算hash值。
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(sourceString));
//创建string builder
StringBuilder sBuilder = new StringBuilder();
//把hash值的数组16进制后合并成字符串
for (int i = data.Length - 1; i >= 0; i--)
{
sBuilder.Append(data[i].ToString("x2"));
}
//return
return sBuilder.ToString();
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="sourceString"></param>
/// <returns></returns>
public static string GetMD5(string sourceString)
{
using (var md5 = MD5.Create())
{
var result = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
var strResult = BitConverter.ToString(result);
return strResult.Replace("-", "");
}
}
/// <summary>
/// 16位的md5
/// </summary>
/// <param name="sourceString"></param>
/// <returns></returns>
public static string GetMD5_16(string sourceString)
{
return GetMD5(sourceString).Substring(8, 16);
}
/// <summary>
/// 取MD5的前几位
/// </summary>
/// <param name="sourceString"></param>
/// <param name="PreLenth"></param>
/// <returns></returns>
public static string GetMD5_Pre(string sourceString, int PreLenth)
{
return GetMD5(sourceString).Substring(0, PreLenth);
}
/// <summary>
/// 畅由移动积分兑换MD5加密方式(和GetMD5得到的数据一样)
/// </summary>
/// <param name="sourceString"></param>
/// <returns></returns>
public static string GetMD5_YD(string sourceString)
{
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
using (var md5 = MD5.Create())
{
var result = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
int j = result.Length;
char[] str = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++)
{
byte byte0 = result[i];
str[k++] = hexDigits[byte0 >> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
}
/// <summary>
/// 验证指定字符串是否和给出的 MD5 Hash值匹配。
/// </summary>
/// <param name="sourceString">原始字符串.</param>
/// <param name="hash">MD5 hash 后的字符串.</param>
/// <returns>
/// <c>true</c>:如果匹配; <c>false</c>:如果不匹配
/// </returns>
/// <remarks></remarks>
/// <exception cref="ArgumentNullException">传入的引用参数为null或空字符串。</exception>
/// <history>
/// 2008/12/18 9:21 Created
/// </history>
public static bool VerifyMd5Hash(string sourceString, string hash)
{
//断言参数异常
//ArgumentAssert.AssertArgumentNotNull(sourceString, "sourceString");
//ArgumentAssert.AssertArgumentNotNull(hash, "hash");
// 计算字符串的 MD5 哈希值
string hashOfInput = GetMD5Hash(sourceString);
// 比较hash
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 计算字符串的 SHA512 哈希值,并将该哈希作为 128 字符的十六进制格式字符串返回。
/// </summary>
/// <param name="sourceString">原始字符串.</param>
/// <returns>SHA512 hash 之后的128位字符串。</returns>
/// <remarks>SHA512 算法的哈希值大小为 512 位。</remarks>
/// <exception cref="ArgumentNullException">传入的引用参数为null或空字符串。</exception>
/// <history>
/// 2008/12/18 10:27 Created
/// </history>
public static string GetSHA512Hash(string sourceString)
{
//断言参数异常
//ArgumentAssert.AssertArgumentNotNull(sourceString, "sourceString");
//创建 SHA512Managed 实例。
SHA512 shaM = new SHA512Managed();
// 把原始字符串转化成一组byte数组并计算hash值。
byte[] data = shaM.ComputeHash(Encoding.Default.GetBytes(sourceString));
//创建string builder
StringBuilder sBuilder = new StringBuilder();
//把hash值的数组16进制后合并成字符串
for (int i = data.Length - 1; i >= 0; i--)
{
sBuilder.Append(data[i].ToString("x2"));
}
//return
return sBuilder.ToString();
}
/// <summary>
/// 验证指定字符串是否和给出的 SHA512 Hash值匹配。
/// </summary>
/// <param name="sourceString">原始字符串.</param>
/// <param name="hash">SHA512 hash 后的字符串.</param>
/// <returns>
/// <c>true</c>:如果匹配; <c>false</c>:如果不匹配
/// </returns>
/// <remarks></remarks>
/// <exception cref="ArgumentNullException">传入的引用参数为null或空字符串。</exception>
/// <history>
/// 2008/12/18 10:31 Created
/// </history>
public static bool VerifySHA512Hash(string sourceString, string hash)
{
//断言参数异常
//ArgumentAssert.AssertArgumentNotNull(sourceString, "sourceString");
//ArgumentAssert.AssertArgumentNotNull(hash, "hash");
// 计算字符串的 MD5 哈希值
string hashOfInput = GetSHA512Hash(sourceString);
// 比较hash
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
#if DEBUG
Console.WriteLine("The correct hash code is: " + hashOfInput);
Console.WriteLine("The false hash code is :" + hash);
#endif
return false;
}
}
/// <summary>
/// 生成一个唯一的字符串16个字符
/// </summary>
/// <returns>唯一字符串</returns>
/// <remarks>
/// </remarks>
/// <history>
/// 2010/7/28 14:31 Created
/// </history>
public static string GenerateUniqueStringID()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
/// <summary>
/// 转换成base64
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// Write At 2012-8-2
public static string ToBase64String(string value)
{
value = Convert.ToBase64String(Encoding.GetEncoding("gb2312").GetBytes(value));
//它将“+”和“/”改成了“!”和“-”,
value = value.Replace('+', '!');
value = value.Replace('/', '-');
return value;
}
/// <summary>
/// Froms the base64 string.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// Write At 2012-8-2
public static string FromBase64String(string value)
{
// //它将“+”和“/”改成了“!”和“-”,
value = value.Replace('!', '+');
value = value.Replace('-', '/');
value = Encoding.GetEncoding("gb2312").GetString(Convert.FromBase64String(value));
return value;
}
/// <summary>
/// HMACSHA1加密并使用Base64编码
/// </summary>
/// <param name="value"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetHMACSHA1(string value, string key)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.UTF8.GetBytes(key);
byte[] dataBuffer = Encoding.UTF8.GetBytes(value);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static String MD5Encode(String origin, String charsetname)
{
var md5 = MD5.Create();
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(origin));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
//所有字符转为小写
return sb.ToString().ToLower();
}
/// <summary>
/// MD5字符串加密
/// </summary>
/// <param name="txt"></param>
/// <returns>加密后字符串</returns>
public static string GenerateMD5(string txt)
{
using (MD5 mi = MD5.Create())
{
byte[] buffer = Encoding.Default.GetBytes(txt);
//开始加密
byte[] newBuffer = mi.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newBuffer.Length; i++)
{
sb.Append(newBuffer[i].ToString("x2"));
}
return sb.ToString();
}
}
#region
//DES、3DES、AES
#endregion
#region
//如果要用C#的私钥进行加密需要使用第三方的加解密组件BouncyCastle来实现
public static void CreateRSAKey()
{
//设置[公钥私钥]文件路径
string privateKeyPath = @"d:\\PrivateKey.xml";
string publicKeyPath = @"d:\\PublicKey.xml";
//创建RSA对象
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
//生成RSA[公钥私钥]
//string privateKey = rsa.ToXmlString(true);
//string publicKey = rsa.ToXmlString(false);
string privateKey = Convert.ToBase64String(rsa.ExportCspBlob(true));
string publicKey = Convert.ToBase64String(rsa.ExportCspBlob(false));
//将密钥写入指定路径
File.WriteAllText(privateKeyPath, privateKey);//文件内包含公钥和私钥
File.WriteAllText(publicKeyPath, publicKey);//文件内只包含公钥
}
/// <summary>
/// rsa公钥加密
/// </summary>
/// <param name="res">加密的明文</param>
/// <param name="publicKey">公钥</param>
/// <returns></returns>
public static string RSA_EncryptData(string res, string publicKey)
{
//C#默认只能使用[公钥]进行加密(想使用[公钥解密]可使用第三方组件BouncyCastle来实现)
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
//将公钥导入到RSA对象中
rsa.FromXmlString(publicKey);
//加密
byte[] data = Encoding.UTF8.GetBytes(res);
var bytes = rsa.Encrypt(data, false);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// rsa私钥解密
/// </summary>
/// <param name="res">解密的密文</param>
/// <param name="privateKey">私钥</param>
/// <returns></returns>
public static string RSA_DecryptData(string res, string privateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
//将私钥导入RSA对象中
rsa.FromXmlString(privateKey);
//解密
byte[] data = Convert.FromBase64String(res);
var bytes = rsa.Decrypt(data, false);
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// rsa私钥签名
/// </summary>
/// <param name="res">签名的数据</param>
/// <param name="privateKey">私钥</param>
/// <returns>返回签名</returns>
public static string RSA_Sign(string res, string privateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
//将私钥导入RSA对象中
rsa.FromXmlString(privateKey);
//将数据使用MD5进行消息摘要然后对摘要进行签名并返回签名数据
byte[] data = Encoding.UTF8.GetBytes(res);
var bytes = rsa.SignData(data, "MD5");
return Convert.ToBase64String(bytes);
}
/// <summary>
/// rsa公钥验证签名
/// </summary>
/// <param name="res">签名的数据</param>
/// <param name="sign">签名</param>
/// <param name="publicKey">公钥</param>
/// <returns></returns>
public static bool RSA_VerifySign(string res, string sign, string publicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
//将公钥导入到RSA对象中
rsa.FromXmlString(publicKey);
//验证签名
byte[] data = Encoding.UTF8.GetBytes(res);
byte[] data_sign = Encoding.UTF8.GetBytes(sign);
return rsa.VerifyData(data, "MD5", data_sign);
}
#endregion
}
}

View File

@ -0,0 +1,119 @@
using System;
namespace XLib.NetCore.Utility
{
/// <summary>
/// 时间帮助类
/// </summary>
public static class TimeUtil
{
/// <summary>
/// 获得时间戳
/// </summary>
/// <returns></returns>
public static long get_time_stamp()
{
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
return (long)ts.TotalMilliseconds;
}
/// <summary>
/// 获得时间戳
/// </summary>
/// <returns></returns>
public static long get_time_stamp(this DateTime time)
{
TimeSpan ts = time.ToUniversalTime() - new DateTime(1970, 1, 1);
return (long)ts.TotalMilliseconds;
}
/// <summary>
/// 获得时间戳 秒
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static int TimeToStamp()
{
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
return (int)ts.TotalSeconds;
}
/// <summary>
/// 时间戳转本地时间-时间戳精确到秒
/// </summary>
public static DateTime ToLocalTimeDateBySeconds(long unix)
{
var dto = DateTimeOffset.FromUnixTimeSeconds(unix);
return dto.ToLocalTime().DateTime;
}
/// <summary>
/// 时间转时间戳Unix-时间戳精确到秒
/// </summary>
public static long ToUnixTimestampBySeconds(DateTime dt)
{
DateTimeOffset dto = new DateTimeOffset(dt);
return dto.ToUnixTimeSeconds();
}
/// <summary>
/// 时间戳转本地时间-时间戳精确到毫秒
/// </summary>
public static DateTime ToLocalTimeDateByMilliseconds(long unix)
{
var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix);
return dto.ToLocalTime().DateTime;
}
/// <summary>
/// 时间转时间戳Unix-时间戳精确到毫秒
/// </summary>
public static long ToUnixTimestampByMilliseconds(DateTime dt)
{
DateTimeOffset dto = new DateTimeOffset(dt);
return dto.ToUnixTimeMilliseconds();
}
/// <summary>
/// 秒转时间文字
/// </summary>
/// <param name="totalSeconds"></param>
/// <returns></returns>
public static string ConvertSecondsToTimeSpanCondensed(long totalSeconds)
{
if (totalSeconds <= 0)
{
return "0秒";
}
long days = totalSeconds / (60 * 60 * 24);
totalSeconds %= (60 * 60 * 24);
long hours = totalSeconds / (60 * 60);
totalSeconds %= (60 * 60);
long minutes = totalSeconds / 60;
long seconds = totalSeconds % 60;
string timeString = "";
if (days > 0)
{
timeString = $"{days}天";
}
if (hours > 0 || timeString.Length > 0) // 如果有天数或者已经添加了小时,则显示小时
{
timeString += $"{hours}小时";
}
if (minutes > 0 || timeString.Length > 0) // 如果有天数或者已经添加了小时,则显示小时
{
timeString += $"{minutes}分钟";
}
timeString += $"{seconds}秒";
return timeString; // 移除开头可能的多余空格
}
}
}

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>帮助类</Title>
<Description>通用的帮助类</Description>
<PackageProjectUrl>git@123.207.203.228:server/XLib.NetCore.Utility.git</PackageProjectUrl>
</PropertyGroup>
</Project>