更新项目配置,新增设备同步模块,优化WebSocket和Swagger配置,增强SCADA系统的免登录接口,支持数据字典项和登录日志的免登录查询与记录。调整Java编译设置,确保更好的开发体验。

This commit is contained in:
geht
2026-04-28 10:23:58 +08:00
parent bbe46dcf2d
commit 142a0bdaba
1013 changed files with 41858 additions and 28 deletions

View File

@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace YY.Admin.Core.Util
{
public class CryptogramUtil
{
public static readonly string CryptoType = "SM2"; // 加密类型
public static readonly string PublicKey = "0484C7466D950E120E5ECE5DD85D0C90EAA85081A3A2BD7C57AE6DC822EFCCBD66620C67B0103FC8DD280E36C3B282977B722AAEC3C56518EDCEBAFB72C5A05312"; // 公钥
public static readonly string PrivateKey = "8EDB615B1D48B8BE188FC0F18EC08A41DF50EA731FA28BF409E6552809E3A111"; // 私钥
public static readonly string SM4_key = "0123456789abcdeffedcba9876543210";
public static readonly string SM4_iv = "595298c7c6fd271f0402f804c33d3f66";
/// <summary>
/// Md5加密
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string Encrypt(string plainText)
{
if (CryptoType == CryptogramEnum.MD5.ToString())
{
return Encrypt(plainText);
}
else if (CryptoType == CryptogramEnum.SM2.ToString())
{
return SM2Encrypt(plainText);
}
else if (CryptoType == CryptogramEnum.SM4.ToString())
{
return SM4EncryptECB(plainText);
}
return plainText;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string Decrypt(string cipherText)
{
if (CryptoType == CryptogramEnum.SM2.ToString())
{
return SM2Decrypt(cipherText);
}
else if (CryptoType == CryptogramEnum.SM4.ToString())
{
return SM4DecryptECB(cipherText);
}
return cipherText;
}
/// <summary>
/// SM2加密
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SM2Encrypt(string plainText)
{
return GMUtil.SM2Encrypt(PublicKey, plainText);
}
/// <summary>
/// SM2解密
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string SM2Decrypt(string cipherText)
{
return GMUtil.SM2Decrypt(PrivateKey, cipherText);
}
/// <summary>
/// SM4加密ECB
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SM4EncryptECB(string plainText)
{
return GMUtil.SM4EncryptECB(SM4_key, plainText);
}
/// <summary>
/// SM4解密ECB
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string SM4DecryptECB(string cipherText)
{
return GMUtil.SM4DecryptECB(SM4_key, cipherText);
}
/// <summary>
/// SM4加密CBC
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SM4EncryptCBC(string plainText)
{
return GMUtil.SM4EncryptCBC(SM4_key, SM4_iv, plainText);
}
/// <summary>
/// SM4解密CBC
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string SM4DecryptCBC(string cipherText)
{
return GMUtil.SM4DecryptCBC(SM4_key, SM4_iv, cipherText);
}
/// <summary>
/// MD5 比较
/// </summary>
/// <param name="text">加密文本</param>
/// <param name="hash">MD5 字符串</param>
/// <param name="uppercase">是否输出大写加密,默认 false</param>
/// <param name="is16">是否输出 16 位</param>
/// <returns>bool</returns>
public static bool Compare(string text, string hash, bool uppercase = false, bool is16 = false)
{
return Compare(Encoding.UTF8.GetBytes(text), hash, uppercase, is16);
}
/// <summary>
/// MD5 加密
/// </summary>
/// <param name="text">加密文本</param>
/// <param name="uppercase">是否输出大写加密,默认 false</param>
/// <param name="is16">是否输出 16 位</param>
/// <returns></returns>
public static string Encrypt(string text, bool uppercase = false, bool is16 = false)
{
return Encrypt(Encoding.UTF8.GetBytes(text), uppercase, is16);
}
/// <summary>
/// MD5 加密
/// </summary>
/// <param name="bytes">字节数组</param>
/// <param name="uppercase">是否输出大写加密,默认 false</param>
/// <param name="is16">是否输出 16 位</param>
/// <returns></returns>
public static string Encrypt(byte[] bytes, bool uppercase = false, bool is16 = false)
{
var data = MD5.HashData(bytes);
var stringBuilder = new StringBuilder();
for (var i = 0; i < data.Length; i++)
{
stringBuilder.Append(data[i].ToString("x2"));
}
var md5String = stringBuilder.ToString();
var hash = !is16 ? md5String : md5String.Substring(8, 16);
return !uppercase ? hash : hash.ToUpper();
}
/// <summary>
/// MD5 比较
/// </summary>
/// <param name="bytes">字节数组</param>
/// <param name="hash">MD5 字符串</param>
/// <param name="uppercase">是否输出大写加密,默认 false</param>
/// <param name="is16">是否输出 16 位</param>
/// <returns>bool</returns>
public static bool Compare(byte[] bytes, string hash, bool uppercase = false, bool is16 = false)
{
var hashOfInput = Encrypt(bytes, uppercase, is16);
return hash.Equals(hashOfInput, StringComparison.OrdinalIgnoreCase);
}
}
}

View File

@@ -0,0 +1,150 @@
using System.Diagnostics;
using System.Management;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace YY.Admin.Core.Util
{
public static class DeviceInfoUtil
{
private static readonly ILoggerService _logger = ContainerLocator.Container.Resolve<ILoggerService>();
private static readonly HttpClient _httpClient = ContainerLocator.Container.Resolve<HttpClient>();
public static async Task<string> GetPublicIpAddressAsync()
{
try
{
using var ipinfoCts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
var response = await _httpClient.GetStringAsync("https://ipinfo.io/ip", ipinfoCts.Token);
return response.Trim();
}
catch (Exception ex)
{
_logger.Error($"获取登录IP地址失败:{ex.Message}");
// 备用方案
try
{
using var ipifyCts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
var response = await _httpClient.GetStringAsync("https://api.ipify.org", ipifyCts.Token);
return response.Trim();
}
catch (Exception ex2)
{
_logger.Error($"获取登录IP地址失败2:{ex2.Message}");
return "无法获取公网IP";
}
}
}
public static IEnumerable<string> GetLocalIpAddresses()
{
try
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return host.AddressList
.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)
.Select(ip => ip.ToString())
.ToList();
}
catch
{
return new List<string> { "无法获取本地IP" };
}
}
public static string GetMachineName()
{
return Environment.MachineName;
}
public static string GetOsVersion()
{
return $"{Environment.OSVersion} ({(Environment.Is64BitOperatingSystem ? "64" : "32")})";
}
public static string GetMacAddress()
{
try
{
var networkInterface = NetworkInterface.GetAllNetworkInterfaces()
.FirstOrDefault(nic => nic.OperationalStatus == OperationalStatus.Up &&
nic.NetworkInterfaceType != NetworkInterfaceType.Loopback);
return networkInterface?.GetPhysicalAddress().ToString() ?? "无法获取MAC地址";
}
catch
{
return "无法获取MAC地址";
}
}
public static string GetProcessorInfo()
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"))
using (var collection = searcher.Get())
{
foreach (var item in collection)
{
return $"{item["Name"]} ({item["NumberOfCores"]}核)";
}
}
}
return Environment.ProcessorCount + " 核处理器";
}
catch
{
return Environment.ProcessorCount + " 核处理器";
}
}
public static long GetTotalMemory()
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"))
using (var collection = searcher.Get())
{
foreach (var item in collection)
{
var totalMemory = Convert.ToInt64(item["TotalPhysicalMemory"]);
return totalMemory / (1024 * 1024); // 转换为MB
}
}
}
return 0;
}
catch
{
return 0;
}
}
public static string GetSystemUpTime()
{
try
{
using (var uptime = new PerformanceCounter("System", "System Up Time"))
{
uptime.NextValue();
var seconds = (int)uptime.NextValue();
var ts = TimeSpan.FromSeconds(seconds);
return $"{ts.Days}天 {ts.Hours}小时 {ts.Minutes}分钟";
}
}
catch
{
return "无法获取运行时间";
}
}
}
}

View File

@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core.Extension;
namespace YY.Admin.Core.Util
{
public static class EnumUtil
{
//
// 摘要:
// 枚举变量是否包含指定标识
//
// 参数:
// value:
// 枚举变量
//
// flag:
// 要判断的标识
public static bool Has(this Enum value, Enum flag)
{
if (value.GetType() != flag.GetType())
{
throw new ArgumentException("flag", "Enumeration identification judgment must be of the same type");
}
ulong num = Convert.ToUInt64(flag);
return (Convert.ToUInt64(value) & num) == num;
}
//
// 摘要:
// 设置标识位
//
// 参数:
// source:
//
// flag:
//
// value:
// 数值
//
// 类型参数:
// T:
public static T Set<T>(this Enum source, T flag, bool value)
{
if (!(source is T))
{
throw new ArgumentException("source", "Enumeration identification judgment must be of the same type");
}
ulong num = Convert.ToUInt64(source);
ulong num2 = Convert.ToUInt64(flag);
num = ((!value) ? (num & ~num2) : (num | num2));
return (T)Enum.ToObject(typeof(T), num);
}
//
// 摘要:
// 获取枚举字段的注释
//
// 参数:
// value:
// 数值
public static string? GetDescription(this Enum value)
{
if (value == null)
{
return null;
}
FieldInfo field = value.GetType().GetField(value.ToString(), BindingFlags.Static | BindingFlags.Public);
if (field == null)
{
return null;
}
DescriptionAttribute customAttribute = field.GetCustomAttribute<DescriptionAttribute>(inherit: false);
if (customAttribute != null && !string.IsNullOrEmpty(customAttribute.Description))
{
return customAttribute.Description;
}
return null;
}
//
// 摘要:
// 获取枚举类型的所有字段注释
//
// 类型参数:
// TEnum:
public static Dictionary<TEnum, string> GetDescriptions<TEnum>() where TEnum : notnull
{
Dictionary<TEnum, string> dictionary = new Dictionary<TEnum, string>();
foreach (KeyValuePair<int, string> description in GetDescriptions(typeof(TEnum)))
{
dictionary.Add((TEnum)Enum.ToObject(typeof(TEnum), description.Key), description.Value);
}
return dictionary;
}
//
// 摘要:
// 获取枚举类型的所有字段注释
//
// 参数:
// enumType:
public static Dictionary<int, string> GetDescriptions(Type enumType)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (FieldInfo fieldInfo in fields)
{
if (fieldInfo.IsStatic)
{
int key = Convert.ToInt32(fieldInfo.GetValue(null));
string value = fieldInfo.Name;
DisplayNameAttribute customAttribute = fieldInfo.GetCustomAttribute<DisplayNameAttribute>(inherit: false);
if (customAttribute != null && !string.IsNullOrEmpty(customAttribute.DisplayName))
{
value = customAttribute.DisplayName;
}
DescriptionAttribute customAttribute2 = fieldInfo.GetCustomAttribute<DescriptionAttribute>(inherit: false);
if (customAttribute2 != null && !string.IsNullOrEmpty(customAttribute2.Description))
{
value = customAttribute2.Description;
}
dictionary[key] = value;
}
}
return dictionary;
}
/// <summary>
/// 获取操作码的查询操作枚举表示
/// </summary>
/// <param name="code">操作码</param>
/// <returns></returns>
public static FilterOperateEnum GetFilterOperate(string code)
{
//code.CheckNotNullOrEmpty("code");
Type type = typeof(FilterOperateEnum);
MemberInfo[] members = type.GetMembers(BindingFlags.Public | BindingFlags.Static);
foreach (MemberInfo member in members)
{
FilterOperateEnum operate = member.Name.CastTo<FilterOperateEnum>();
if (operate.ToOperateCode() == code)
{
return operate;
}
}
throw new NotSupportedException("获取操作码的查询操作枚举表示时不支持代码:" + code);
}
/// <summary>
/// 把查询操作的枚举表示转换为操作码
/// </summary>
/// <param name="operate">查询操作的枚举表示</param>
public static string ToOperateCode(this FilterOperateEnum operate)
{
Type type = operate.GetType();
MemberInfo[] members = type.GetMember(operate.CastTo<string>());
if (members.Length == 0)
{
return null;
}
OperateCodeAttribute attribute = members[0].GetAttribute<OperateCodeAttribute>();
return attribute?.Code;
}
}
}

View File

@@ -0,0 +1,471 @@
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math.EC.Multiplier;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509;
namespace YY.Admin.Core.Util
{
/**
*
* 用BC的注意点
* 这个版本的BC对SM3withSM2的结果为asn1格式的r和s如果需要直接拼接的r||s需要自己转换。下面rsAsn1ToPlainByteArray、rsPlainByteArrayToAsn1就在干这事。
* 这个版本的BC对SM2的结果为C1||C2||C3据说为旧标准新标准为C1||C3||C2用新标准的需要自己转换。下面被注释掉的changeC1C2C3ToC1C3C2、changeC1C3C2ToC1C2C3就在干这事。java版的高版本有加上C1C3C2csharp版没准以后也会加但目前还没有java版的目前可以初始化时“ SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);”。
*
*/
public class GM
{
private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
private static ECDomainParameters ecDomainParameters = new(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
/**
*
* @param msg
* @param userId
* @param privateKey
* @return r||s直接拼接byte数组的rs
*/
public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
}
/**
* @param msg
* @param userId
* @param privateKey
* @return rs in <b>asn1 format</b>
*/
public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(true, new ParametersWithID(privateKey, userId));
signer.BlockUpdate(msg, 0, msg.Length);
byte[] sig = signer.GenerateSignature();
return sig;
}
/**
*
* @param msg
* @param userId
* @param rs r||s直接拼接byte数组的rs
* @param publicKey
* @return
*/
public static bool VerifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, AsymmetricKeyParameter publicKey)
{
if (rs == null || msg == null || userId == null) return false;
if (rs.Length != RS_LEN * 2) return false;
return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
}
/**
*
* @param msg
* @param userId
* @param rs in <b>asn1 format</b>
* @param publicKey
* @return
*/
public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(false, new ParametersWithID(publicKey, userId));
signer.BlockUpdate(msg, 0, msg.Length);
return signer.VerifySignature(sign);
}
/**
* bc加解密使用旧标c1||c2||c3此方法在加密后调用将结果转化为c1||c3||c2
* @param c1c2c3
* @return
*/
private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
{
int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
const int c3Len = 32; //new SM3Digest().getDigestSize();
byte[] result = new byte[c1c2c3.Length];
Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
return result;
}
/**
* bc加解密使用旧标c1||c3||c2此方法在解密前调用将密文转化为c1||c2||c3再去解密
* @param c1c3c2
* @return
*/
private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
{
int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
const int c3Len = 32; //new SM3Digest().GetDigestSize();
byte[] result = new byte[c1c3c2.Length];
Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
return result;
}
/**
* c1||c3||c2
* @param data
* @param key
* @return
*/
public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
{
return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
}
/**
* c1||c3||c2
* @param data
* @param key
* @return
*/
public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
{
return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
}
/**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
/**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, key);
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
/**
* @param bytes
* @return
*/
public static byte[] Sm3(byte[] bytes)
{
SM3Digest digest = new();
digest.BlockUpdate(bytes, 0, bytes.Length);
byte[] result = DigestUtilities.DoFinal(digest);
return result;
}
private const int RS_LEN = 32;
private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
{
// for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
// r and s are the result of mod n, so they should be less than n and have length<=32
byte[] rs = rOrS.ToByteArray();
if (rs.Length == RS_LEN) return rs;
else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
else if (rs.Length < RS_LEN)
{
byte[] result = new byte[RS_LEN];
Arrays.Fill(result, (byte)0);
Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
return result;
}
else
{
throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
}
}
/**
* BC的SM3withSM2签名得到的结果的rs是asn1格式的这个方法转化成直接拼接r||s
* @param rsDer rs in asn1 format
* @return sign result in plain byte array
*/
private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
{
Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
byte[] result = new byte[RS_LEN * 2];
Buffer.BlockCopy(r, 0, result, 0, r.Length);
Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
return result;
}
/**
* BC的SM3withSM2验签需要的rs是asn1格式的这个方法将直接拼接r||s的字节数组转化成asn1格式
* @param sign in plain byte array
* @return rs result in asn1 format
*/
private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
{
if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
Asn1EncodableVector v = new Asn1EncodableVector
{
new DerInteger(r),
new DerInteger(s)
};
return new DerSequence(v).GetEncoded("DER");
}
// 生成公私匙对
public static AsymmetricCipherKeyPair GenerateKeyPair()
{
ECKeyPairGenerator kpGen = new();
kpGen.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));
return kpGen.GenerateKeyPair();
}
public static ECPrivateKeyParameters GetPrivatekeyFromD(BigInteger d)
{
return new ECPrivateKeyParameters(d, ecDomainParameters);
}
public static ECPublicKeyParameters GetPublickeyFromXY(BigInteger x, BigInteger y)
{
return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
}
public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
{
FileStream fileStream = null;
try
{
//file.DirectoryName + "\\" + file.Name
fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
return certificate.GetPublicKey();
}
catch (Exception)
{
//log.Error(file.Name + "读取失败,异常:" + e);
}
finally
{
if (fileStream != null)
fileStream.Close();
}
return null;
}
public class Sm2Cert
{
public AsymmetricKeyParameter privateKey;
public AsymmetricKeyParameter publicKey;
public string certId;
}
private static byte[] ToByteArray(int i)
{
byte[] byteArray = new byte[4];
byteArray[0] = (byte)(i >> 24);
byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
byteArray[2] = (byte)((i & 0xFFFF) >> 8);
byteArray[3] = (byte)(i & 0xFF);
return byteArray;
}
/**
* 字节数组拼接
*
* @param params
* @return
*/
private static byte[] Join(params byte[][] byteArrays)
{
List<byte> byteSource = new();
for (int i = 0; i < byteArrays.Length; i++)
{
byteSource.AddRange(byteArrays[i]);
}
byte[] data = byteSource.ToArray();
return data;
}
/**
* 密钥派生函数
*
* @param Z
* @param klen
* 生成klen字节数长度的密钥
* @return
*/
private static byte[] KDF(byte[] Z, int klen)
{
int ct = 1;
int end = (int)Math.Ceiling(klen * 1.0 / 32);
List<byte> byteSource = new();
for (int i = 1; i < end; i++)
{
byteSource.AddRange(Sm3(Join(Z, ToByteArray(ct))));
ct++;
}
byte[] last = Sm3(Join(Z, ToByteArray(ct)));
if (klen % 32 == 0)
{
byteSource.AddRange(last);
}
else
byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
return byteSource.ToArray();
}
public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
c.Init(false, new ParametersWithIV(key, iv));
return c.DoFinal(cipher);
}
public static byte[] Sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (plain.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
c.Init(true, new ParametersWithIV(key, iv));
return c.DoFinal(plain);
}
public static byte[] Sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
//NoPadding 的情况下需要校验数据长度是16的倍数.
if (plain.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(true, key);
return c.DoFinal(plain);
}
public static byte[] Sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(false, key);
return c.DoFinal(cipher);
}
public const string SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
public const string SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
public const string SM4_ECB_PKCS7PADDING = "SM4/ECB/PKCS7Padding";
public const string SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding";
/**
* cfca官网CSP沙箱导出的sm2文件
* @param pem 二进制原文
* @param pwd 密码
* @return
*/
public static Sm2Cert ReadSm2File(byte[] pem, string pwd)
{
Sm2Cert sm2Cert = new();
Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pem);
// ASN1Integer asn1Integer = (ASN1Integer) asn1Sequence.getObjectAt(0); //version=1
Asn1Sequence priSeq = (Asn1Sequence)asn1Sequence[1];//private key
Asn1Sequence pubSeq = (Asn1Sequence)asn1Sequence[2];//public key and x509 cert
// ASN1ObjectIdentifier sm2DataOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(0);
// ASN1ObjectIdentifier sm4AlgOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(1);
Asn1OctetString priKeyAsn1 = (Asn1OctetString)priSeq[2];
byte[] key = KDF(System.Text.Encoding.UTF8.GetBytes(pwd), 32);
byte[] priKeyD = Sm4DecryptCBC(Arrays.CopyOfRange(key, 16, 32),
priKeyAsn1.GetOctets(),
Arrays.CopyOfRange(key, 0, 16), SM4_CBC_PKCS7PADDING);
sm2Cert.privateKey = GetPrivatekeyFromD(new BigInteger(1, priKeyD));
// log.Info(Hex.toHexString(priKeyD));
// ASN1ObjectIdentifier sm2DataOidPub = (ASN1ObjectIdentifier) pubSeq.getObjectAt(0);
Asn1OctetString pubKeyX509 = (Asn1OctetString)pubSeq[1];
X509Certificate x509 = new X509CertificateParser().ReadCertificate(pubKeyX509.GetOctets());
sm2Cert.publicKey = x509.GetPublicKey();
sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进制有啥其他进制要求的自己改改
return sm2Cert;
}
/**
*
* @param cert
* @return
*/
public static Sm2Cert ReadSm2X509Cert(byte[] cert)
{
Sm2Cert sm2Cert = new();
X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert);
sm2Cert.publicKey = x509.GetPublicKey();
sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进制有啥其他进制要求的自己改改
return sm2Cert;
}
public static byte[] ZeroIv(string algo)
{
IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
int blockSize = cipher.GetBlockSize();
byte[] iv = new byte[blockSize];
Arrays.Fill(iv, (byte)0);
return iv;
}
}
}

View File

@@ -0,0 +1,147 @@
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Encoders;
using System.Text;
namespace YY.Admin.Core.Util
{
/// <summary>
/// GM工具类
/// </summary>
public class GMUtil
{
/// <summary>
/// SM2加密
/// </summary>
/// <param name="publicKeyHex"></param>
/// <param name="data_string"></param>
/// <returns></returns>
public static string SM2Encrypt(string publicKeyHex, string data_string)
{
// 如果是130位公钥.NET使用的话把开头的04截取掉
if (publicKeyHex.Length == 130)
{
publicKeyHex = publicKeyHex.Substring(2, 128);
}
// 公钥X前64位
string x = publicKeyHex.Substring(0, 64);
// 公钥Y后64位
string y = publicKeyHex.Substring(64);
// 获取公钥对象
AsymmetricKeyParameter publicKey1 = GM.GetPublickeyFromXY(new BigInteger(x, 16), new BigInteger(y, 16));
// Sm2Encrypt: C1C3C2
// Sm2EncryptOld: C1C2C3
byte[] digestByte = GM.Sm2Encrypt(Encoding.UTF8.GetBytes(data_string), publicKey1);
string strSM2 = Hex.ToHexString(digestByte);
return strSM2;
}
/// <summary>
/// SM2解密
/// </summary>
/// <param name="privateKey_string"></param>
/// <param name="encryptedData_string"></param>
/// <returns></returns>
public static string SM2Decrypt(string privateKey_string, string encryptedData_string)
{
//return Encoding.Default.GetString(SM2Util.Decrypt(Hex.Decode(privateKey_string), Hex.Decode(encryptedData_string)));
if (!encryptedData_string.StartsWith("04"))
encryptedData_string = "04" + encryptedData_string;
BigInteger d = new(privateKey_string, 16);
// 先拿到私钥对象用ECPrivateKeyParameters 或 AsymmetricKeyParameter 都可以
// ECPrivateKeyParameters bcecPrivateKey = GmUtil.GetPrivatekeyFromD(d);
AsymmetricKeyParameter bcecPrivateKey = GM.GetPrivatekeyFromD(d);
byte[] byToDecrypt = Hex.Decode(encryptedData_string);
byte[] byDecrypted = GM.Sm2Decrypt(byToDecrypt, bcecPrivateKey);
string strDecrypted = Encoding.UTF8.GetString(byDecrypted);
return strDecrypted;
}
/// <summary>
/// SM4加密ECB
/// </summary>
/// <param name="key_string"></param>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SM4EncryptECB(string key_string, string plainText)
{
byte[] key = Hex.Decode(key_string);
byte[] bs = GM.Sm4EncryptECB(key, Encoding.UTF8.GetBytes(plainText), GM.SM4_ECB_PKCS7PADDING);//NoPadding 的情况下需要校验数据长度是16的倍数. 使用 HandleSm4Padding 处理
return Hex.ToHexString(bs);
}
/// <summary>
/// SM4解密ECB
/// </summary>
/// <param name="key_string"></param>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string SM4DecryptECB(string key_string, string cipherText)
{
byte[] key = Hex.Decode(key_string);
byte[] bs = GM.Sm4DecryptECB(key, Hex.Decode(cipherText), GM.SM4_ECB_PKCS7PADDING);
return Encoding.UTF8.GetString(bs);
}
/// <summary>
/// SM4加密CBC
/// </summary>
/// <param name="key_string"></param>
/// <param name="iv_string"></param>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SM4EncryptCBC(string key_string, string iv_string, string plainText)
{
byte[] key = Hex.Decode(key_string);
byte[] iv = Hex.Decode(iv_string);
byte[] bs = GM.Sm4EncryptCBC(key, Encoding.UTF8.GetBytes(plainText), iv, GM.SM4_CBC_PKCS7PADDING);
return Hex.ToHexString(bs);
}
/// <summary>
/// SM4解密CBC
/// </summary>
/// <param name="key_string"></param>
/// <param name="iv_string"></param>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string SM4DecryptCBC(string key_string, string iv_string, string cipherText)
{
byte[] key = Hex.Decode(key_string);
byte[] iv = Hex.Decode(iv_string);
byte[] bs = GM.Sm4DecryptCBC(key, Hex.Decode(cipherText), iv, GM.SM4_CBC_PKCS7PADDING);
return Encoding.UTF8.GetString(bs);
}
/// <summary>
/// 补足 16 进制字符串的 0 字符,返回不带 0x 的16进制字符串
/// </summary>
/// <param name="input"></param>
/// <param name="mode">1表示加密0表示解密</param>
/// <returns></returns>
private static byte[] HandleSm4Padding(byte[] input, int mode)
{
if (input == null)
{
return null;
}
byte[] ret = (byte[])null;
if (mode == 1)
{
int p = 16 - input.Length % 16;
ret = new byte[input.Length + p];
Array.Copy(input, 0, ret, 0, input.Length);
for (int i = 0; i < p; i++)
{
ret[input.Length + i] = (byte)p;
}
}
else
{
int p = input[input.Length - 1];
ret = new byte[input.Length - p];
Array.Copy(input, 0, ret, 0, input.Length - p);
}
return ret;
}
}
}

View File

@@ -0,0 +1,74 @@
using System.Globalization;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
namespace YY.Admin.Core.Util;
/// <summary>
/// 与 JeecgBoot <c>PasswordUtil.encrypt(username, plainPassword, salt)</c> 对齐:
/// 算法 <c>PBEWithMD5AndDES</c>,迭代 1000 次;明文为 <b>用户名 UTF-8</b>,口令为明文密码;盐为字符串转字节(与 Java 一致建议使用 UTF-8
/// </summary>
public static class JeecgPasswordUtil
{
/// <summary>与 Java PasswordUtil 中 ITERATIONCOUNT 一致</summary>
public const int IterationCount = 1000;
/// <summary>
/// 生成与 Jeecg 数据库 <c>sys_user.password</c> 一致的十六进制密文(小写)。
/// </summary>
/// <param name="username">登录账号Jeecg 的 username</param>
/// <param name="plainPassword">明文密码</param>
/// <param name="salt">Jeecg 用户表 salt 字段字符串</param>
/// <param name="saltEncoding">盐字节编码Jeecg 服务端 JVM 多为 UTF-8建议固定 UTF-8</param>
public static string Encrypt(string username, string plainPassword, string salt, Encoding? saltEncoding = null)
{
saltEncoding ??= Encoding.UTF8;
byte[] saltBytes = saltEncoding.GetBytes(salt);
byte[] plainBytes = Encoding.UTF8.GetBytes(username);
// PKCS#5 Scheme1MD5+ DES/CBC/PKCS7与 Java JCE PBEWithMD5AndDES 一致
var generator = new Pkcs5S1ParametersGenerator(new MD5Digest());
generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(plainPassword.ToCharArray()), saltBytes, IterationCount);
// 派生 DES 密钥 + IV各 64 bit
ParametersWithIV keyIv = (ParametersWithIV)generator.GenerateDerivedParameters("DES", 64, 64);
var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEngine()), new Pkcs7Padding());
cipher.Init(true, keyIv);
byte[] output = new byte[cipher.GetOutputSize(plainBytes.Length)];
int len = cipher.ProcessBytes(plainBytes, 0, plainBytes.Length, output, 0);
len += cipher.DoFinal(output, len);
if (len < output.Length)
Array.Resize(ref output, len);
return BytesToHexLower(output);
}
/// <summary>
/// 校验明文密码是否与 Jeecg 存储的十六进制密文一致。
/// </summary>
public static bool Verify(string username, string plainPassword, string salt, string storedPasswordHex, Encoding? saltEncoding = null)
{
if (string.IsNullOrEmpty(storedPasswordHex))
return false;
string computed = Encrypt(username, plainPassword, salt, saltEncoding);
return string.Equals(computed, storedPasswordHex, StringComparison.OrdinalIgnoreCase);
}
private static string BytesToHexLower(byte[] src)
{
if (src == null || src.Length == 0)
return string.Empty;
var sb = new StringBuilder(src.Length * 2);
foreach (byte b in src)
sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
return sb.ToString();
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YY.Admin.Core
{
/// <summary>
/// 模糊查询条件
/// </summary>
public class Search
{
/// <summary>
/// 字段名称集合
/// </summary>
public List<string> Fields { get; set; }
/// <summary>
/// 关键字
/// </summary>
public string? Keyword { get; set; }
}
/// <summary>
/// 筛选过滤条件
/// </summary>
public class Filter
{
/// <summary>
/// 过滤条件
/// </summary>
public FilterLogicEnum? Logic { get; set; }
/// <summary>
/// 筛选过滤条件子项
/// </summary>
public IEnumerable<Filter>? Filters { get; set; }
/// <summary>
/// 字段名称
/// </summary>
public string? Field { get; set; }
/// <summary>
/// 逻辑运算符
/// </summary>
public FilterOperatorEnum? Operator { get; set; }
/// <summary>
/// 字段值
/// </summary>
public object? Value { get; set; }
}
/// <summary>
/// 过滤条件基类
/// </summary>
public abstract class BaseFilter
{
/// <summary>
/// 模糊查询条件
/// </summary>
public Search? Search { get; set; }
/// <summary>
/// 模糊查询关键字
/// </summary>
public string? Keyword { get; set; }
/// <summary>
/// 筛选过滤条件
/// </summary>
public Filter? Filter { get; set; }
}
}

View File

@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace YY.Admin.Core
{
/// <summary>
/// 全局分页查询输入参数
/// </summary>
public class BasePageInput : BaseFilter
{
/// <summary>
/// 当前页码
/// </summary>
public virtual int Page { get; set; } = 1;
/// <summary>
/// 页码容量
/// </summary>
//[Range(0, 100, ErrorMessage = "页码容量超过最大限制")]
public virtual int PageSize { get; set; } = 20;
/// <summary>
/// 排序字段
/// </summary>
public virtual string Field { get; set; }
/// <summary>
/// 排序方向
/// </summary>
public virtual string Order { get; set; }
/// <summary>
/// 降序排序
/// </summary>
public virtual string DescStr { get; set; } = "descending";
}
}

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YY.Admin.Core
{
/// <summary>
/// 分页请求基类
/// </summary>
public class PagedRequestBase : BindableBase
{
/// <summary>
/// 页码从1开始
/// </summary>
public int Page { get; set; } = 1;
/// <summary>
/// 页容量
/// </summary>
public int PageSize { get; set; } = 10;
/// <summary>
/// 搜索关键词
/// </summary>
public string SearchKey { get; set; } = string.Empty;
}
///// <summary>
///// 用户分页查询输入
///// </summary>
//public class PageUserInput : PagedRequestBase
//{
// /// <summary>
// /// 机构ID
// /// </summary>
// public long OrgId { get; set; }
// /// <summary>
// /// 租户ID
// /// </summary>
// public long TenantId { get; set; }
// /// <summary>
// /// 账号
// /// </summary>
// public string Account { get; set; } = string.Empty;
// /// <summary>
// /// 真实姓名
// /// </summary>
// public string RealName { get; set; } = string.Empty;
// /// <summary>
// /// 职位名称
// /// </summary>
// public string PosName { get; set; } = string.Empty;
// /// <summary>
// /// 电话
// /// </summary>
// public string Phone { get; set; } = string.Empty;
//}
}

View File

@@ -0,0 +1,152 @@

//
//
//
//using Org.BouncyCastle.Crypto;
//using Org.BouncyCastle.Crypto.Parameters;
//using Org.BouncyCastle.Math;
//using Org.BouncyCastle.Math.EC;
//extern alias OldBC;
//extern alias NewBC;
//// 使用时通过别名限定
//OldBC::BouncyCastle.Crypto.ECPoint oldEcPoint;
//NewBC::BouncyCastle.Cryptography.ECPoint newEcPoint;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
namespace YY.Admin.Core.Util;
public class Cipher
{
private int ct;
private ECPoint p2;
private SM3Digest sm3keybase;
private SM3Digest sm3c3;
private readonly byte[] key;
private byte keyOff;
public Cipher()
{
ct = 1;
key = new byte[32];
keyOff = 0;
}
public static byte[] ByteConvert32Bytes(BigInteger n)
{
if (n == null)
return null;
byte[] tmpd;
if (n.ToByteArray().Length == 33)
{
tmpd = new byte[32];
Array.Copy(n.ToByteArray(), 1, tmpd, 0, 32);
}
else if (n.ToByteArray().Length == 32)
{
tmpd = n.ToByteArray();
}
else
{
tmpd = new byte[32];
for (int i = 0; i < 32 - n.ToByteArray().Length; i++)
{
tmpd[i] = 0;
}
Array.Copy(n.ToByteArray(), 0, tmpd, 32 - n.ToByteArray().Length, n.ToByteArray().Length);
}
return tmpd;
}
private void Reset()
{
sm3keybase = new SM3Digest();
sm3c3 = new SM3Digest();
byte[] p = ByteConvert32Bytes(p2.Normalize().XCoord.ToBigInteger());
sm3keybase.BlockUpdate(p, 0, p.Length);
sm3c3.BlockUpdate(p, 0, p.Length);
p = ByteConvert32Bytes(p2.Normalize().YCoord.ToBigInteger());
sm3keybase.BlockUpdate(p, 0, p.Length);
ct = 1;
NextKey();
}
private void NextKey()
{
var sm3keycur = new SM3Digest(this.sm3keybase);
sm3keycur.Update((byte)(ct >> 24 & 0xff));
sm3keycur.Update((byte)(ct >> 16 & 0xff));
sm3keycur.Update((byte)(ct >> 8 & 0xff));
sm3keycur.Update((byte)(ct & 0xff));
sm3keycur.DoFinal(key, 0);
keyOff = 0;
ct++;
}
public ECPoint Init_enc(SM2 sm2, ECPoint userKey)
{
AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
BigInteger k = ecpriv.D;
ECPoint c1 = ecpub.Q;
p2 = userKey.Multiply(k);
Reset();
return c1;
}
public void Encrypt(byte[] data)
{
sm3c3.BlockUpdate(data, 0, data.Length);
for (int i = 0; i < data.Length; i++)
{
if (keyOff == key.Length)
{
NextKey();
}
data[i] ^= key[keyOff++];
}
}
public void Init_dec(BigInteger userD, ECPoint c1)
{
p2 = c1.Multiply(userD);
Reset();
}
public void Decrypt(byte[] data)
{
for (int i = 0; i < data.Length; i++)
{
if (keyOff == key.Length)
{
NextKey();
}
data[i] ^= key[keyOff++];
}
sm3c3.BlockUpdate(data, 0, data.Length);
}
public void Dofinal(byte[] c3)
{
byte[] p = ByteConvert32Bytes(p2.Normalize().YCoord.ToBigInteger());
sm3c3.BlockUpdate(p, 0, p.Length);
sm3c3.DoFinal(c3, 0);
Reset();
}
}

View File

@@ -0,0 +1,120 @@

//
//
//
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
namespace YY.Admin.Core.Util;
public class SM2
{
public static SM2 Instance
{
get
{
return new SM2();
}
}
public static SM2 InstanceTest
{
get
{
return new SM2();
}
}
public static readonly string[] sm2_param = {
"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF",// p,0
"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC",// a,1
"28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93",// b,2
"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123",// n,3
"32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7",// gx,4
"BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0" // gy,5
};
public string[] ecc_param = sm2_param;
public readonly BigInteger ecc_p;
public readonly BigInteger ecc_a;
public readonly BigInteger ecc_b;
public readonly BigInteger ecc_n;
public readonly BigInteger ecc_gx;
public readonly BigInteger ecc_gy;
public readonly ECCurve ecc_curve;
public readonly ECPoint ecc_point_g;
public readonly ECDomainParameters ecc_bc_spec;
public readonly ECKeyPairGenerator ecc_key_pair_generator;
private SM2()
{
ecc_param = sm2_param;
ecc_p = new BigInteger(ecc_param[0], 16);
ecc_a = new BigInteger(ecc_param[1], 16);
ecc_b = new BigInteger(ecc_param[2], 16);
ecc_n = new BigInteger(ecc_param[3], 16);
ecc_gx = new BigInteger(ecc_param[4], 16);
ecc_gy = new BigInteger(ecc_param[5], 16);
ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b, null, null);
ecc_point_g = ecc_curve.CreatePoint(ecc_gx, ecc_gy);
ecc_bc_spec = new ECDomainParameters(ecc_curve, ecc_point_g, ecc_n);
ECKeyGenerationParameters ecc_ecgenparam;
ecc_ecgenparam = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom());
ecc_key_pair_generator = new ECKeyPairGenerator();
ecc_key_pair_generator.Init(ecc_ecgenparam);
}
public virtual byte[] Sm2GetZ(byte[] userId, ECPoint userKey)
{
var sm3 = new SM3Digest();
byte[] p;
// userId length
int len = userId.Length * 8;
sm3.Update((byte)(len >> 8 & 0x00ff));
sm3.Update((byte)(len & 0x00ff));
// userId
sm3.BlockUpdate(userId, 0, userId.Length);
// a,b
p = ecc_a.ToByteArray();
sm3.BlockUpdate(p, 0, p.Length);
p = ecc_b.ToByteArray();
sm3.BlockUpdate(p, 0, p.Length);
// gx,gy
p = ecc_gx.ToByteArray();
sm3.BlockUpdate(p, 0, p.Length);
p = ecc_gy.ToByteArray();
sm3.BlockUpdate(p, 0, p.Length);
// x,y
p = userKey.AffineXCoord.ToBigInteger().ToByteArray();
sm3.BlockUpdate(p, 0, p.Length);
p = userKey.AffineYCoord.ToBigInteger().ToByteArray();
sm3.BlockUpdate(p, 0, p.Length);
// Z
byte[] md = new byte[sm3.GetDigestSize()];
sm3.DoFinal(md, 0);
return md;
}
}

View File

@@ -0,0 +1,177 @@

//
//
//
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities.Encoders;
using System.Text;
namespace YY.Admin.Core.Util;
/// <summary>
/// SM2工具类
/// </summary>
public class SM2Util
{
/// <summary>
/// 加密
/// </summary>
/// <param name="publicKey_string"></param>
/// <param name="data_string"></param>
/// <returns></returns>
public static string Encrypt(string publicKey_string, string data_string)
{
var publicKey = Hex.Decode(publicKey_string);
var data = Encoding.UTF8.GetBytes(data_string);
return Encrypt(publicKey, data);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="privateKey_string"></param>
/// <param name="encryptedData_string"></param>
/// <returns></returns>
public static string Decrypt(string privateKey_string, string encryptedData_string)
{
var privateKey = Hex.Decode(privateKey_string);
var encryptedData = Hex.Decode(encryptedData_string);
var de_str = SM2Util.Decrypt(privateKey, encryptedData);
string plainText = Encoding.UTF8.GetString(de_str);
return plainText;
}
public static void GenerateKeyPair()
{
SM2 sm2 = SM2.Instance;
AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
BigInteger privateKey = ecpriv.D;
ECPoint publicKey = ecpub.Q;
Console.Out.WriteLine("公钥: " + Encoding.ASCII.GetString(Hex.Encode(publicKey.GetEncoded())).ToUpper());
Console.Out.WriteLine("私钥: " + Encoding.ASCII.GetString(Hex.Encode(privateKey.ToByteArray())).ToUpper());
}
public static string Encrypt(byte[] publicKey, byte[] data)
{
if (null == publicKey || publicKey.Length == 0)
{
return null;
}
if (data == null || data.Length == 0)
{
return null;
}
byte[] source = new byte[data.Length];
Array.Copy(data, 0, source, 0, data.Length);
var cipher = new Cipher();
SM2 sm2 = SM2.Instance;
ECPoint userKey = sm2.ecc_curve.DecodePoint(publicKey);
ECPoint c1 = cipher.Init_enc(sm2, userKey);
cipher.Encrypt(source);
byte[] c3 = new byte[32];
cipher.Dofinal(c3);
string sc1 = Encoding.ASCII.GetString(Hex.Encode(c1.GetEncoded()));
string sc2 = Encoding.ASCII.GetString(Hex.Encode(source));
string sc3 = Encoding.ASCII.GetString(Hex.Encode(c3));
return (sc1 + sc2 + sc3).ToUpper();
}
public static byte[] Decrypt(byte[] privateKey, byte[] encryptedData)
{
if (null == privateKey || privateKey.Length == 0)
{
return null;
}
if (encryptedData == null || encryptedData.Length == 0)
{
return null;
}
string data = Encoding.ASCII.GetString(Hex.Encode(encryptedData));
byte[] c1Bytes = Hex.Decode(Encoding.ASCII.GetBytes(data.Substring(0, 130)));
int c2Len = encryptedData.Length - 97;
byte[] c2 = Hex.Decode(Encoding.ASCII.GetBytes(data.Substring(130, 2 * c2Len)));
byte[] c3 = Hex.Decode(Encoding.ASCII.GetBytes(data.Substring(130 + 2 * c2Len, 64)));
SM2 sm2 = SM2.Instance;
var userD = new BigInteger(1, privateKey);
ECPoint c1 = sm2.ecc_curve.DecodePoint(c1Bytes);
var cipher = new Cipher();
cipher.Init_dec(userD, c1);
cipher.Decrypt(c2);
cipher.Dofinal(c3);
return c2;
}
//[STAThread]
//public static void Main()
//{
// GenerateKeyPair();
// String plainText = "ererfeiisgod";
// byte[] sourceData = Encoding.Default.GetBytes(plainText);
// //下面的秘钥可以使用generateKeyPair()生成的秘钥内容
// // 国密规范正式私钥
// String prik = "3690655E33D5EA3D9A4AE1A1ADD766FDEA045CDEAA43A9206FB8C430CEFE0D94";
// // 国密规范正式公钥
// String pubk = "04F6E0C3345AE42B51E06BF50B98834988D54EBC7460FE135A48171BC0629EAE205EEDE253A530608178A98F1E19BB737302813BA39ED3FA3C51639D7A20C7391A";
// System.Console.Out.WriteLine("加密: ");
// String cipherText = SM2Utils.Encrypt(Hex.Decode(pubk), sourceData);
// System.Console.Out.WriteLine(cipherText);
// System.Console.Out.WriteLine("解密: ");
// plainText = Encoding.Default.GetString(SM2Utils.Decrypt(Hex.Decode(prik), Hex.Decode(cipherText)));
// System.Console.Out.WriteLine(plainText);
// Console.ReadLine();
//}
/// <summary>
/// SM2加密
/// </summary>
/// <param name="plainText">明文</param>
/// <returns>密文</returns>
public static String (String plainText)
{
// 国密规范正式公钥
String pubk = "04F6E0C3345AE42B51E06BF50B98834988D54EBC7460FE135A48171BC0629EAE205EEDE253A530608178A98F1E19BB737302813BA39ED3FA3C51639D7A20C7391A";
byte[] sourceData = Encoding.Default.GetBytes(plainText);
String cipherText = SM2Util.Encrypt(Hex.Decode(pubk), sourceData);
return cipherText;
}
/// <summary>
/// SM2解密
/// </summary>
/// <param name="cipherText">密文</param>
/// <returns>明文</returns>
public static string (String cipherText)
{
// 国密规范正式私钥
String prik = "3690655E33D5EA3D9A4AE1A1ADD766FDEA045CDEAA43A9206FB8C430CEFE0D94";
String plainText = Encoding.Default.GetString(SM2Util.Decrypt(Hex.Decode(prik), Hex.Decode(cipherText)));
return plainText;
}
}

View File

@@ -0,0 +1,28 @@
using System.Globalization;
namespace YY.Admin.Core.Util
{
public class StringUtil
{
/// <summary>
/// HTML实体编码转换为C#/WPF支持的Unicode转义格式
/// </summary>
/// <param name="htmlEntity"></param>
/// <returns></returns>
public static string ConvertHtmlEntityToUnicode(string htmlEntity)
{
if (string.IsNullOrEmpty(htmlEntity))
return string.Empty;
if (htmlEntity.StartsWith("&#x") && htmlEntity.EndsWith(";"))
{
string hexCode = htmlEntity.Substring(3, htmlEntity.Length - 4);
if (int.TryParse(hexCode, NumberStyles.HexNumber, null, out int unicodeValue))
{
return char.ConvertFromUtf32(unicodeValue);
}
}
return htmlEntity;
}
}
}