首次提交

This commit is contained in:
lzjyzq2
2023-03-02 22:57:29 +08:00
parent 295157d946
commit 505bf37dab
16 changed files with 1577 additions and 0 deletions

View File

@ -0,0 +1,460 @@
using System;
using Org.BouncyCastle.Utilities.Encoders;
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.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using System.IO;
using System.Runtime.InteropServices;
namespace SMCryptoUtils
{
[ClassInterface(ClassInterfaceType.None)]
public class EasyGmUtils:IEasyGmUtils
{
private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
/**
*
* @param msg
* @param userId
* @param privateKey
* @return r||s直接拼接byte数组的rs
*/
public byte[] signSm3WithSm2(byte[] msg, byte[] userId, byte[] privateKeyBytes)
{
ECPrivateKeyParameters privateKeyParameters = getPrivatekeyFromD(new BigInteger(1, privateKeyBytes));
return rsAsn1ToPlainByteArray(signSm3WithSm2Asn1Rs(msg, userId, privateKeyParameters));
}
/**
* @param msg
* @param userId
* @param privateKey
* @return rs in <b>asn1 format</b>
*/
public byte[] signSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
try
{
ISigner signer = SignerUtilities.InitSigner("SM3withSM2", true, privateKey, new SecureRandom());
signer.BlockUpdate(msg, 0, msg.Length);
byte[] sig = signer.GenerateSignature();
return sig;
}
catch (Exception e)
{
//log.Error("SignSm3WithSm2Asn1Rs error: " + e.Message, e);
return null;
}
}
/**
*
* @param msg
* @param userId
* @param rs r||s直接拼接byte数组的rs
* @param publicKey
* @return
*/
public bool verifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, byte[] publicKeyBytes)
{
if (rs == null || msg == null || userId == null) return false;
if (rs.Length != RS_LEN * 2) return false;
if (publicKeyBytes.Length != 64 && publicKeyBytes.Length != 65) throw new ArgumentException("err key length");
BigInteger x, y;
if (publicKeyBytes.Length > 64)
{
x = fromUnsignedByteArray(publicKeyBytes, 1, 32);
y = fromUnsignedByteArray(publicKeyBytes, 33, 32);
}
else
{
x = fromUnsignedByteArray(publicKeyBytes, 0, 32);
y = fromUnsignedByteArray(publicKeyBytes, 32, 32);
}
ECPublicKeyParameters publicKey = getPublickeyFromXY(x, y);
return verifySm3WithSm2Asn1Rs(msg, userId, rsPlainByteArrayToAsn1(rs), publicKey);
}
public BigInteger fromUnsignedByteArray(byte[] var0, int var1, int var2)
{
byte[] var3 = var0;
if (var1 != 0 || var2 != var0.Length)
{
var3 = new byte[var2];
Array.Copy(var0, var1, var3, 0, var2);
}
return new BigInteger(1, var3);
}
/**
*
* @param msg
* @param userId
* @param rs in <b>asn1 format</b>
* @param publicKey
* @return
*/
public bool verifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
{
try
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(false, publicKey);
signer.BlockUpdate(msg, 0, msg.Length);
return signer.VerifySignature(sign);
}
catch (Exception e)
{
//log.Error("VerifySm3WithSm2Asn1Rs error: " + e.Message, e);
return false;
}
}
/**
* 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 byte[] sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
{
return sm2DecryptOld(changeC1C3C2ToC1C2C3(data), key);
}
/**
* c1||c3||c2
* @param data
* @param key
* @return
*/
public byte[] sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
{
return changeC1C2C3ToC1C3C2(sm2EncryptOld(data, key));
}
/**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public byte[] sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
{
try
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
//log.Error("Sm2EncryptOld error: " + e.Message, e);
return null;
}
}
/**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public byte[] sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
{
try
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, key);
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
//log.Error("Sm2DecryptOld error: " + e.Message, e);
return null;
}
}
/**
* @param bytes
* @return
*/
public byte[] sm3(byte[] bytes)
{
try
{
SM3Digest digest = new SM3Digest();
digest.BlockUpdate(bytes, 0, bytes.Length);
byte[] result = DigestUtilities.DoFinal(digest);
return result;
}
catch (Exception e)
{
//log.Error("Sm3 error: " + e.Message, e);
return null;
}
}
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();
v.Add(new DerInteger(r));
v.Add(new DerInteger(s));
try
{
return new DerSequence(v).GetEncoded("DER");
}
catch (IOException e)
{
//log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
return null;
}
}
public 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) throw new ArgumentException("err data length");
try
{
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);
}
catch (Exception e)
{
//log.Error("Sm4DecryptCBC error: " + e.Message, e);
return null;
}
}
public 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) throw new ArgumentException("err data length");
try
{
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);
}
catch (Exception e)
{
//log.Error("Sm4EncryptCBC error: " + e.Message, e);
return null;
}
}
public byte[] sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (plain.Length % 16 != 0) throw new ArgumentException("err data length");
try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(true, key);
return c.DoFinal(plain);
}
catch (Exception e)
{
//log.Error("Sm4EncryptECB error: " + e.Message, e);
return null;
}
}
public byte[] sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(false, key);
return c.DoFinal(cipher);
}
catch (Exception e)
{
//log.Error("Sm4DecryptECB error: " + e.Message, e);
return null;
}
}
public ECPrivateKeyParameters getPrivatekeyFromD(BigInteger d)
{
return new ECPrivateKeyParameters(d, ecDomainParameters);
}
public ECPublicKeyParameters getPublickeyFromXY(BigInteger x, BigInteger y)
{
return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
}
public byte[] sm4Encrypt(byte[] keyBytes, byte[] plain)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
// if (plain.length % 16 != 0) throw new RuntimeException("err data length");
try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
c.Init(true, key);
return c.DoFinal(plain);
}
catch (Exception e)
{
return null;
}
}
public byte[] sm4Decrypt(byte[] keyBytes, byte[] cipher)
{
// if (keyBytes.length != 16) throw new RuntimeException("err key length");
if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
c.Init(false, key);
return c.DoFinal(cipher);
}
catch (Exception e)
{
return null;
}
}
public const String SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
public const String SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
public const String SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding";
public byte[] zeroIv(String algo)
{
try
{
IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
int blockSize = cipher.GetBlockSize();
byte[] iv = new byte[blockSize];
Arrays.Fill(iv, (byte)0);
return iv;
}
catch (Exception e)
{
//log.Error("ZeroIv error: " + e.Message, e);
return null;
}
}
}
}

View File

@ -0,0 +1,34 @@
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMCryptoUtils
{
public interface IEasyGmUtils
{
BigInteger fromUnsignedByteArray(byte[] var0, int var1, int var2);
ECPrivateKeyParameters getPrivatekeyFromD(BigInteger d);
ECPublicKeyParameters getPublickeyFromXY(BigInteger x, BigInteger y);
byte[] signSm3WithSm2(byte[] msg, byte[] userId, byte[] privateKeyBytes);
byte[] signSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey);
byte[] sm2Decrypt(byte[] data, AsymmetricKeyParameter key);
byte[] sm2DecryptOld(byte[] data, AsymmetricKeyParameter key);
byte[] sm2Encrypt(byte[] data, AsymmetricKeyParameter key);
byte[] sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey);
byte[] sm3(byte[] bytes);
byte[] sm4Decrypt(byte[] keyBytes, byte[] cipher);
byte[] sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, string algo);
byte[] sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo);
byte[] sm4Encrypt(byte[] keyBytes, byte[] plain);
byte[] sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, string algo);
byte[] sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo);
bool verifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, byte[] publicKeyBytes);
bool verifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey);
byte[] zeroIv(string algo);
}
}

17
SMCryptoUtils/ISMUtil.cs Normal file
View File

@ -0,0 +1,17 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMCryptoUtils
{
public interface ISMUtil
{
string decrypt(string data, string appId, string appSecret);
string encrypt(string data, string appId, string appSecret);
string sign(JObject jsonObject, string appSecret, string privateKey);
bool verify(JObject jsonObject, string appSecret, string publicKey, string responseSign);
}
}

View File

@ -0,0 +1,15 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMCryptoUtils
{
public interface ISignUtil
{
string getObjString(object obj);
string getSignText(JObject jsonObject, string appSecret);
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("SMCryptoUtils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SMCryptoUtils")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(true)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("164f1097-1277-42dd-a4ad-dc9bd59be320")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{164F1097-1277-42DD-A4AD-DC9BD59BE320}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SMCryptoUtils</RootNamespace>
<AssemblyName>SMCryptoUtils</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<RegisterForComInterop>true</RegisterForComInterop>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="EasyGmUtils.cs" />
<Compile Include="IEasyGmUtils.cs" />
<Compile Include="ISignUtil.cs" />
<Compile Include="ISMUtil.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SignUtil.cs" />
<Compile Include="SMUtil.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json">
<Version>9.0.1</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32014.148
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SMCryptoUtils", "SMCryptoUtils.csproj", "{164F1097-1277-42DD-A4AD-DC9BD59BE320}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SMCryptoUtilsTest", "..\SMCryptoUtilsTest\SMCryptoUtilsTest.csproj", "{8B808C3C-450E-4771-AB15-11B980CEC34B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{164F1097-1277-42DD-A4AD-DC9BD59BE320}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{164F1097-1277-42DD-A4AD-DC9BD59BE320}.Debug|Any CPU.Build.0 = Debug|Any CPU
{164F1097-1277-42DD-A4AD-DC9BD59BE320}.Release|Any CPU.ActiveCfg = Release|Any CPU
{164F1097-1277-42DD-A4AD-DC9BD59BE320}.Release|Any CPU.Build.0 = Release|Any CPU
{8B808C3C-450E-4771-AB15-11B980CEC34B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8B808C3C-450E-4771-AB15-11B980CEC34B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8B808C3C-450E-4771-AB15-11B980CEC34B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8B808C3C-450E-4771-AB15-11B980CEC34B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E73D7C28-BBBC-4505-A75C-E46856110DA8}
EndGlobalSection
EndGlobal

91
SMCryptoUtils/SMUtil.cs Normal file
View File

@ -0,0 +1,91 @@
using System;
using Org.BouncyCastle.Utilities.Encoders;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices;
namespace SMCryptoUtils
{
[ClassInterface(ClassInterfaceType.None)]
public class SMUtil:ISMUtil
{
private readonly static EasyGmUtils easyGmUtils = new EasyGmUtils();
private readonly static SignUtil signUtil = new SignUtil();
/**
* 加密
*
* @param data
* @param appId
* @param appSecret
* @return
*/
public string encrypt(string data, string appId, string appSecret)
{
//加密流程
//用appId加密appSecret获取新秘钥
byte[] appSecretEncData = easyGmUtils.sm4Encrypt(Encoding.UTF8.GetBytes(appId.Substring(0, 16)), Encoding.UTF8.GetBytes(appSecret));
//新秘钥串
byte[] secKey = Encoding.UTF8.GetBytes(Hex.ToHexString(appSecretEncData).ToUpper().Substring(0, 16));
//加密0数据
string encryptDataStr = Hex.ToHexString(easyGmUtils.sm4Encrypt(secKey, Encoding.UTF8.GetBytes(data))).ToUpper();
return encryptDataStr;
}
/**
* 解密
*
* @param data
* @param appId
* @param appSecret
* @return
*/
public string decrypt(string data, string appId, string appSecret)
{
byte[] appSecretEncDataDecode = easyGmUtils.sm4Encrypt(Encoding.UTF8.GetBytes(appId.Substring(0, 16)), Encoding.UTF8.GetBytes(appSecret));
byte[] secKeyDecode = Encoding.UTF8.GetBytes(Hex.ToHexString(appSecretEncDataDecode).ToUpper().Substring(0, 16));
string decryptDataStr = Encoding.UTF8.GetString(easyGmUtils.sm4Decrypt(secKeyDecode, Hex.Decode(data)));
return decryptDataStr;
}
/**
* 签名
*
* @param jsonObject
* @param appSecret
* @param privateKey
* @return
*/
public string sign(JObject jsonObject, string appSecret, string privateKey)
{
// 获取签名串
byte[] signText = Encoding.UTF8.GetBytes(signUtil.getSignText(jsonObject, appSecret));
byte[] userId = Encoding.UTF8.GetBytes(appSecret);
byte[] prvkey = Base64.Decode(privateKey);
string responseSign = Base64.ToBase64String(easyGmUtils.signSm3WithSm2(signText, userId, prvkey));
return responseSign;
}
/**
* 验签
*
* @param jsonObject
* @param appSecret
* @param publicKey
* @param responseSign
* @return
*/
public Boolean verify(JObject jsonObject, string appSecret, string publicKey, string responseSign)
{
//验签
byte[] msg = Encoding.UTF8.GetBytes(signUtil.getSignText(jsonObject, appSecret));
byte[] userIdDecode = Encoding.UTF8.GetBytes(appSecret);
byte[] pubkey = Base64.Decode(publicKey);
byte[] signData = Base64.Decode(responseSign);
return easyGmUtils.verifySm3WithSm2(msg, userIdDecode, signData, pubkey);
}
}
}

271
SMCryptoUtils/SignUtil.cs Normal file
View File

@ -0,0 +1,271 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SMCryptoUtils
{
[ClassInterface(ClassInterfaceType.None)]
public class SignUtil:ISignUtil
{
private static List<string> ignoreSign = new List<string>() { "signData", "encData", "extra" };
public string getSignText(JObject jsonObject, string appSecret)
{
SortedDictionary<string, string> signMap = new SortedDictionary<string, string>(StringComparer.Ordinal);
foreach (var entry in jsonObject)
{
if (!string.IsNullOrEmpty(entry.Value.ToString()) && !ignoreSign.Contains(entry.Key))
{
signMap.Add(entry.Key, getValue(entry.Value));
}
}
List<string> list = new List<string>();
foreach (var entry in signMap)
{
if (!string.IsNullOrEmpty(getObjString(entry.Value)))
{
list.Add((string)entry.Key + "=" + (string)entry.Value + "&");
}
}
int size = list.Count();
string[] arrayToSort = (string[])list.ToArray();
Array.Sort(arrayToSort, new CaseInsensitiveComparer());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; ++i)
{
sb.Append(arrayToSort[i]);
}
string signText = sb.Append("key=").Append(appSecret).ToString();
return signText;
}
public string getObjString(Object obj)
{
return obj == null ? "" : (string)obj;
}
private string getValue(Object value)
{
return value is string ? getObjString(value) : treeJsonParam(value);
}
private static string treeJsonParam(Object value)
{
string jsonParam = null;
if (value is Dictionary<Object, Object>)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
Dictionary<Object, Object> nestedMap = (Dictionary<Object, Object>)value;
foreach (var entry in nestedMap)
{
treeNestedMap.Add(entry.Key.ToString(), entry.Value);
}
jsonParam = JsonConvert.SerializeObject(treeParams(treeNestedMap), Formatting.None);
}
else if (value is List<Object>)
{
List<Object> ar = (List<Object>)value;
jsonParam = JsonConvert.SerializeObject(treeList(ar), Formatting.None);
}
else if (value is JObject)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
JObject nestedMap = (JObject)value;
foreach (var entry in nestedMap)
{
treeNestedMap.Add(entry.Key.ToString(), entry.Value);
}
jsonParam = JsonConvert.SerializeObject(treeParams(treeNestedMap), Formatting.None);
}
else if (value is JArray)
{
JArray jarr = (JArray)value;
jsonParam = JsonConvert.SerializeObject(treeJsonArray(jarr), Formatting.None);
}
else if (value is JValue)
{
JValue jval = (JValue)value;
if (jval != null)
jsonParam = jval.Value.ToString();
}
else if (value is JProperty)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
JProperty nestedMap = (JProperty)value;
treeNestedMap.Add(nestedMap.Name, nestedMap.Value);
jsonParam = JsonConvert.SerializeObject(treeParams(treeNestedMap), Formatting.None);
}
else
{
jsonParam = value.ToString();
}
return jsonParam;
}
private static SortedDictionary<string, Object> treeParams(SortedDictionary<string, Object> param)
{
if (param == null)
{
return new SortedDictionary<string, Object>(StringComparer.Ordinal);
}
else
{
SortedDictionary<string, Object> treeParam = new SortedDictionary<string, Object>(StringComparer.Ordinal);
while (true)
{
foreach (var entry in param)
{
string key = (string)entry.Key;
Object value = entry.Value;
if (value is Dictionary<Object, Object>)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
Dictionary<Object, Object> nestedMap = (Dictionary<Object, Object>)value;
foreach (var nestedEntry in nestedMap)
{
treeNestedMap.Add(nestedEntry.Key.ToString(), nestedEntry.Value);
}
treeParam.Add(key, treeParams(treeNestedMap));
}
else if (value is List<Object>)
{
List<Object> ar = (List<Object>)value;
treeParam.Add(key, treeList(ar));
}
else if (value is JArray)
{
JArray ar = (JArray)value;
treeParam.Add(key, treeJsonArray(ar));
}
else if (value is JObject)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
JObject nestedMap = (JObject)value;
foreach (var nestedEntry in nestedMap)
{
treeNestedMap.Add(nestedEntry.Key.ToString(), nestedEntry.Value);
}
treeParam.Add(key, treeParams(treeNestedMap));
}
else if (value is JValue)
{
JValue jval = (JValue)value;
if (jval != null && !string.IsNullOrEmpty(jval.ToString()))
treeParam.Add(key, jval.ToString());
}
else if (value is JProperty)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
JProperty nestedMap = (JProperty)value;
treeNestedMap.Add(nestedMap.Name, nestedMap.Value);
treeParam.Add(key, treeParams(treeNestedMap));
}
else if (!"".Equals(value) && value != null)
{
treeParam.Add(key, value.ToString());
}
}
return treeParam;
}
}
}
private static List<Object> treeList(List<Object> list)
{
if (list != null && list.Count() != 0)
{
JArray jsonArray = new JArray();
int size = list.Count();
for (int i = 0; i < size; ++i)
{
jsonArray.Add(list[i]);
}
return treeJsonArray(jsonArray);
}
else
{
return null;
}
}
private static List<Object> treeJsonArray(JArray jarr)
{
if (jarr != null && jarr.Count() != 0)
{
List<Object> jsonArray = new List<Object>();
int size = jarr.Count();
for (int i = 0; i < size; ++i)
{
Object value = jarr[i];
if (value is List<Object>)
{
List<Object> ar = (List<Object>)value;
jsonArray.Add(treeList(ar));
}
else if (value is JArray)
{
JArray ar = (JArray)value;
jsonArray.Add(treeJsonArray(ar));
}
else if (value is JObject)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
JObject nestedMap = (JObject)value;
foreach (var nestedEntry in nestedMap)
{
treeNestedMap.Add(nestedEntry.Key.ToString(), nestedEntry.Value);
}
jsonArray.Add(treeParams(treeNestedMap));
}
else if (value is JValue)
{
JValue jval = (JValue)value;
if (jval != null && !string.IsNullOrEmpty(jval.ToString()))
jsonArray.Add(jval.ToString());
}
else if (value is JProperty)
{
SortedDictionary<string, Object> treeNestedMap = new SortedDictionary<string, Object>(StringComparer.Ordinal);
JProperty nestedMap = (JProperty)value;
treeNestedMap.Add(nestedMap.Name, nestedMap.Value);
jsonArray.Add(treeParams(treeNestedMap));
}
else if (!"".Equals(value))
{
jsonArray.Add(value.ToString());
}
}
return jsonArray;
}
else
{
return null;
}
}
}
}