(json);
+ }
+}
diff --git a/Assets/Scripts/SecretTest/Encrypt.cs.meta b/Assets/Scripts/SecretTest/Encrypt.cs.meta
new file mode 100644
index 0000000..1d92eea
--- /dev/null
+++ b/Assets/Scripts/SecretTest/Encrypt.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c28ed6bccc39c83488cf9104a5466ec6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretTest/Program.cs b/Assets/Scripts/SecretTest/Program.cs
new file mode 100644
index 0000000..9663d59
--- /dev/null
+++ b/Assets/Scripts/SecretTest/Program.cs
@@ -0,0 +1,43 @@
+using SecretUtils;
+using System;
+using System.Text;
+using SecretUtils.Crypto;
+
+namespace SecretTest
+{
+ class Program
+ {
+ static void Main(string[] args)
+ {
+ //国密sm4
+ //string sm4key= Sm4Base.GenerateKeyString();
+ //string sm4key = "698ee3f90666d6a8e62d73b3c1f5f4f3";
+ //string data = "测试示例testtest!!!";
+ //byte[] cipher= Sm4Base.EncryptCBC(Encoding.UTF8.GetBytes(data), sm4key);
+ //Console.WriteLine(Hex.ToHexString(cipher, 0, cipher.Length));
+ //byte[] plain = Sm4Base.DecryptCBC(cipher, sm4key);
+ //Console.WriteLine(Encoding.UTF8.GetString(plain));
+
+ //国密sm2
+
+ //SM2KeyPair ms2key =Sm2Base.GenerateKey();
+ var data2 = Encoding.UTF8.GetBytes("这是测试!!!!!");
+ SM2KeyPair keys = Sm2Base.GenerateKey();
+
+
+ Sm2Base.GenerateKeyFile(keys.pubKey, @"C:\Users\Zeng\Desktop\pukfile.puk");
+ byte[] signValue = Sm2Base.Sign(keys.priKey, data2);
+ bool b = Sm2Base.VerifySign(keys.pubKey, data2, signValue);
+
+
+
+ byte[] cipher2 = Sm2Base.Encrypt(keys.pubKey, data2);
+
+ byte[] plain = Sm2Base.Decrypt(keys.priKey, cipher2);
+
+ //byte[] ciphersm4 = Sm2Base.Encrypt(, Encoding.UTF8.GetBytes(data2));
+ Console.WriteLine(Encoding.UTF8.GetString(plain));
+ Console.ReadKey();
+ }
+ }
+}
diff --git a/Assets/Scripts/SecretTest/Program.cs.meta b/Assets/Scripts/SecretTest/Program.cs.meta
new file mode 100644
index 0000000..951e3bf
--- /dev/null
+++ b/Assets/Scripts/SecretTest/Program.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1fe64dfa24c11dd4daf67eff4af6bef9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretTest/SM4Example.cs b/Assets/Scripts/SecretTest/SM4Example.cs
new file mode 100644
index 0000000..5ced56e
--- /dev/null
+++ b/Assets/Scripts/SecretTest/SM4Example.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Text;
+using Org.BouncyCastle.Crypto.Engines;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Utilities.Encoders;
+using UnityEngine;
+
+
+class SM4Example: MonoBehaviour
+{
+ // SM4
+ public static byte[] Encrypt(byte[] plainText, byte[] key)
+ {
+ var engine = new SM4Engine();
+ engine.Init(true, new KeyParameter(key)); // true ʾģʽ
+ byte[] encrypted = new byte[plainText.Length];
+ engine.ProcessBlock(plainText, 0, encrypted, 0);
+ return encrypted;
+ }
+
+
+ // SM4
+ public static byte[] Decrypt(byte[] cipherText, byte[] key)
+ {
+ var engine = new SM4Engine();
+ engine.Init(false, new KeyParameter(key)); // false ʾģʽ
+ byte[] decrypted = new byte[cipherText.Length];
+ engine.ProcessBlock(cipherText, 0, decrypted, 0);
+ return decrypted;
+ }
+
+
+
+
+ void Start()
+ {
+ // Կ
+ byte[] key = Encoding.UTF8.GetBytes("1234567890abcdef"); // 128 λԿ (16 ֽ)
+ byte[] plainText = Encoding.UTF8.GetBytes("111");
+
+
+ //
+ byte[] encrypted = Encrypt(plainText, key);
+ Console.WriteLine("ܺ (Hex): " + Hex.ToHexString(encrypted));
+
+
+ //
+ byte[] decrypted = Decrypt(encrypted, key);
+ Console.WriteLine("ܺ: " + Encoding.UTF8.GetString(decrypted));
+ }
+}
\ No newline at end of file
diff --git a/Assets/Scripts/SecretTest/SM4Example.cs.meta b/Assets/Scripts/SecretTest/SM4Example.cs.meta
new file mode 100644
index 0000000..3e321c1
--- /dev/null
+++ b/Assets/Scripts/SecretTest/SM4Example.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ffef5b89e3b54aa4889fc4c5bcc2f13c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils.meta b/Assets/Scripts/SecretUtils.meta
new file mode 100644
index 0000000..c60fa50
--- /dev/null
+++ b/Assets/Scripts/SecretUtils.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 670bff74082f5164fa61ae219fc3a928
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto.meta b/Assets/Scripts/SecretUtils/Crypto.meta
new file mode 100644
index 0000000..e21a9f4
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: faa4e0685fc887041a994f2b25edc720
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto/MD5Util.cs b/Assets/Scripts/SecretUtils/Crypto/MD5Util.cs
new file mode 100644
index 0000000..10f9872
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/MD5Util.cs
@@ -0,0 +1,33 @@
+using System.Security.Cryptography;
+
+namespace SecretUtils.Crypto
+{
+ public class MD5Util
+ {
+ public static string GetMD5(byte[] inputBye, string charset)
+ {
+ string retStr;
+ MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
+
+ //创建md5对象
+ //byte[] inputBye;
+ byte[] outputBye;
+
+ ////使用GB2312编码方式把字符串转化为字节数组.
+ //try
+ //{
+ // inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
+ //}
+ //catch (Exception ex)
+ //{
+ // inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
+ // Console.WriteLine(ex);
+ //}
+ outputBye = m5.ComputeHash(inputBye);
+ //retStr= Base64.ToBase64String(outputBye);
+ retStr = System.BitConverter.ToString(outputBye);
+ retStr = retStr.Replace("-", "").ToUpper();
+ return retStr;
+ }
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Crypto/MD5Util.cs.meta b/Assets/Scripts/SecretUtils/Crypto/MD5Util.cs.meta
new file mode 100644
index 0000000..4a7a815
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/MD5Util.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f9924e70bf2fc3f49bdeae25d75ec96b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM2KeyPair.cs b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPair.cs
new file mode 100644
index 0000000..f73875f
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPair.cs
@@ -0,0 +1,13 @@
+namespace SecretUtils.Crypto
+{
+ public class SM2KeyPair
+ {
+ public byte[] priKey;//私钥
+ public byte[] pubKey;//公钥
+ public SM2KeyPair(byte[] priKey, byte[] pubKey) {
+ this.priKey = priKey;
+ this.pubKey = pubKey;
+ }
+
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM2KeyPair.cs.meta b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPair.cs.meta
new file mode 100644
index 0000000..7ab7435
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPair.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: efae25b363eda4642848a41177052aaf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM2KeyPairString.cs b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPairString.cs
new file mode 100644
index 0000000..be1d1b2
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPairString.cs
@@ -0,0 +1,16 @@
+using Org.BouncyCastle.Utilities.Encoders;
+
+namespace SecretUtils.Crypto
+{
+ public class SM2KeyPairString
+ {
+ public string priKey;//私钥
+ public string pubKey;//公钥
+ public SM2KeyPairString(SM2KeyPair sm2Key)
+ {
+ this.priKey =Hex.ToHexString(sm2Key.priKey,0, sm2Key.priKey.Length);
+ this.pubKey = Hex.ToHexString(sm2Key.pubKey, 0, sm2Key.pubKey.Length);
+ }
+
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM2KeyPairString.cs.meta b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPairString.cs.meta
new file mode 100644
index 0000000..1489e2e
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM2KeyPairString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: af956316c840ded498011323a674ea6c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM2Util.cs b/Assets/Scripts/SecretUtils/Crypto/SM2Util.cs
new file mode 100644
index 0000000..9c0d36a
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM2Util.cs
@@ -0,0 +1,320 @@
+using System;
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Asn1.GM;
+using Org.BouncyCastle.Asn1.Pkcs;
+using Org.BouncyCastle.Asn1.Sec;
+using Org.BouncyCastle.Asn1.X509;
+using Org.BouncyCastle.Asn1.X9;
+using Org.BouncyCastle.Crypto;
+using Org.BouncyCastle.Crypto.Engines;
+using Org.BouncyCastle.Crypto.Generators;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Crypto.Signers;
+using Org.BouncyCastle.Math;
+using Org.BouncyCastle.Math.EC;
+using Org.BouncyCastle.Security;
+using Org.BouncyCastle.Utilities.Encoders;
+
+namespace SecretUtils.Crypto
+{
+ internal class SM2Util
+ {
+ private static readonly byte[] defaultUserID = System.Text.Encoding.ASCII.GetBytes("1234567812345678");
+ /**
+ * 获取der格式中的纯公钥数据
+ */
+ public static byte[] GetPublicKeyFormDER(byte[] derData)
+ {
+
+ SubjectPublicKeyInfo info = SubjectPublicKeyInfo.GetInstance(derData);
+ return info.PublicKeyData.GetBytes();
+ }
+
+ /**
+ * 获取der编码格式中的纯私钥数据
+ */
+ public static byte[] GetPrivateKeyFormDER(byte[] derData)
+ {
+
+ PrivateKeyInfo pinfo = PrivateKeyInfo.GetInstance(derData);
+ ECPrivateKeyStructure cpk = ECPrivateKeyStructure.GetInstance(pinfo.ParsePrivateKey());
+
+ int length = 32;
+ byte[] bytes = cpk.GetKey().ToByteArray();
+ if (bytes.Length == length)
+ {
+ return bytes;
+ }
+
+ int start = bytes[0] == 0 ? 1 : 0;
+ int count = bytes.Length - start;
+
+ if (count > length)
+ {
+ throw new ArgumentException("privateKey data is error");
+ }
+
+ byte[] tmp = new byte[length];
+ Buffer.BlockCopy(bytes, start, tmp, tmp.Length - count, count);
+ return tmp;
+ }
+
+
+
+ /**
+ * 生成sm2公私钥对
+ * @return
+ */
+ public static SM2KeyPair GenerateKeyPair()
+ {
+ X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1");
+ ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
+ KeyGenerationParameters kgp = new ECKeyGenerationParameters(parameters, new SecureRandom());
+ ECKeyPairGenerator ecKeyPairGenerator = new ECKeyPairGenerator();
+ ecKeyPairGenerator.Init(kgp);
+ ECPrivateKeyParameters ecpriv = null;
+ ECPublicKeyParameters ecpub = null;
+ // int count = 0;
+ do
+ {
+ AsymmetricCipherKeyPair keypair = ecKeyPairGenerator.GenerateKeyPair();
+ ecpriv = (ECPrivateKeyParameters)keypair.Private;
+ ecpub = (ECPublicKeyParameters)keypair.Public;
+ } while (ecpriv == null || ecpriv.D.Equals(BigInteger.Zero)
+ || ecpriv.D.CompareTo(sm2p256v1.N) >= 0 || ecpriv.D.SignValue <= 0);
+ byte[] privKey = FormartBigNum(ecpriv.D, 32);
+ return new SM2KeyPair(privKey, ecpub.Q.GetEncoded());
+ }
+
+ /**
+ * 格式化BigInteger,bg.toByteArray()获取到的字节数据长度不固定,因此需要格式化为固定长度
+ * @param bg 大数
+ * @param needLength 所需要的长度
+ * @return
+ */
+ private static byte[] FormartBigNum(BigInteger bg, int needLength)
+ {
+
+ byte[] tmp = new byte[needLength];
+ byte[] bgByte = bg.ToByteArray();
+ if (bgByte == null)
+ {
+ return null;
+ }
+
+ if (bgByte.Length > needLength)
+ {
+ Buffer.BlockCopy(bgByte, bgByte.Length - needLength, tmp, 0, needLength);
+ }
+ else if (bgByte.Length == needLength)
+ {
+ tmp = bgByte;
+ }
+ else
+ {
+ Buffer.BlockCopy(bgByte, 0, tmp, needLength - bgByte.Length, bgByte.Length);
+ }
+
+
+ return tmp;
+ }
+
+ /**
+ * sm2加密
+ *
+ */
+ public static byte[] Encrypt(byte[] pubkey, byte[] srcData)
+ {
+ X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1");
+ SecureRandom random = new SecureRandom();
+ ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
+ ECPublicKeyParameters pubKeyParameters = new ECPublicKeyParameters(sm2p256v1.Curve.DecodePoint(pubkey), parameters);
+ SM2Engine engine = new SM2Engine();
+ ParametersWithRandom pwr = new ParametersWithRandom(pubKeyParameters, new SecureRandom());
+ engine.Init(true, pwr);
+ return encodeSM2CipherToDER(engine.ProcessBlock(srcData, 0, srcData.Length));
+ }
+
+ /**
+ * sm2解密
+ */
+ public static byte[] Decrypt(byte[] privkey, byte[] srcData)
+ {
+ X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1");
+ SecureRandom random = new SecureRandom();
+ ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
+
+ ECPrivateKeyParameters priKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, privkey), parameters);
+ SM2Engine engine = new SM2Engine();
+ ParametersWithRandom pwr = new ParametersWithRandom(priKeyParameters, new SecureRandom());
+ engine.Init(false, priKeyParameters);
+ byte[] c1c2c3 = decodeDERSM2Cipher(srcData);
+ return engine.ProcessBlock(c1c2c3, 0, c1c2c3.Length);
+ }
+
+ /**
+ * sm2签名
+ * userId使用默认:1234567812345678
+ * @param privateKey 私钥,二进制数据
+ * @param sourceData 待签名数据
+ * @return 返回der编码的签名值
+ * @throws CryptoException
+ */
+ public static byte[] Sign(byte[] privateKey, byte[] sourceData)
+ {
+ return Sign(defaultUserID, privateKey, sourceData);
+ }
+
+ /**
+ * sm2签名
+ * @param userId ID值,若无约定,使用默认:1234567812345678
+ * @param privateKey 私钥,二进制数据
+ * @param sourceData 待签名数据
+ * @return 返回der编码的签名值
+ * @throws CryptoException
+ */
+ public static byte[] Sign(byte[] userId, byte[] privateKey, byte[] sourceData)
+ {
+ X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1");
+ ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
+ ECPrivateKeyParameters priKeyParameters = new ECPrivateKeyParameters(new BigInteger(1,privateKey),parameters);
+ SM2Signer signer = new SM2Signer();
+ ICipherParameters param = null;
+ ParametersWithRandom pwr = new ParametersWithRandom(priKeyParameters, new SecureRandom());
+ if (userId != null) {
+ param = new ParametersWithID(pwr, userId);
+ } else {
+ param = pwr;
+ }
+ signer.Init(true, param);
+ signer.BlockUpdate(sourceData, 0, sourceData.Length);
+ return signer.GenerateSignature();
+ }
+
+ /**
+ * sm2验签
+ *
userId使用默认:1234567812345678
+ * @param publicKey 公钥,二进制数据
+ * @param sourceData 待验签数据
+ * @param signData 签名值
+ * @return 返回是否成功
+ */
+ public static Boolean VerifySign(byte[] publicKey, byte[] sourceData, byte[] signData)
+ {
+ return VerifySign(defaultUserID, publicKey, sourceData, signData);
+ }
+
+ /**
+ * sm2验签
+ * @param userId ID值,若无约定,使用默认:1234567812345678
+ * @param publicKey 公钥,二进制数据
+ * @param sourceData 待验签数据
+ * @param signData 签名值
+ * @return 返回是否成功
+ */
+ public static Boolean VerifySign(byte[] userId, byte[] publicKey, byte[] sourceData, byte[] signData)
+ {
+
+ if (publicKey.Length == 64)
+ {
+ byte[] tmp = new byte[65];
+ Buffer.BlockCopy(publicKey, 0, tmp, 1, publicKey.Length);
+ tmp[0] = 0x04;
+ publicKey = tmp;
+ }
+
+ X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1");
+ ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
+ ECPublicKeyParameters pubKeyParameters = new ECPublicKeyParameters(sm2p256v1.Curve.DecodePoint(publicKey), parameters);
+ SM2Signer signer = new SM2Signer();
+ ICipherParameters param;
+ if (userId != null)
+ {
+ param = new ParametersWithID(pubKeyParameters, userId);
+ }
+ else
+ {
+ param = pubKeyParameters;
+ }
+ signer.Init(false, param);
+ signer.BlockUpdate(sourceData, 0, sourceData.Length);
+ return signer.VerifySignature(signData);
+ }
+
+ public static byte[] encodeSM2CipherToDER(byte[] cipher)
+ {
+ int startPos = 1;
+
+ int curveLength = 32;
+ int digestLength = 32;
+
+ byte[] c1x = new byte[curveLength];
+ Buffer.BlockCopy(cipher, startPos, c1x, 0, c1x.Length);
+ startPos += c1x.Length;
+
+ byte[] c1y = new byte[curveLength];
+ Buffer.BlockCopy(cipher, startPos, c1y, 0, c1y.Length);
+ startPos += c1y.Length;
+
+ byte[] c2 = new byte[cipher.Length - c1x.Length - c1y.Length - 1 - digestLength];
+ Buffer.BlockCopy(cipher, startPos, c2, 0, c2.Length);
+ startPos += c2.Length;
+
+ byte[] c3 = new byte[digestLength];
+ Buffer.BlockCopy(cipher, startPos, c3, 0, c3.Length);
+
+ Asn1Encodable[] arr = new Asn1Encodable[4];
+ arr[0] = new DerInteger(new BigInteger(1, c1x));//
+ arr[1] = new DerInteger(new BigInteger(1, c1y));//
+ arr[2] = new DerOctetString(c3);
+ arr[3] = new DerOctetString(c2);
+ DerSequence ds = new DerSequence(arr);
+ return ds.GetEncoded(Asn1Encodable.Der);
+ }
+
+ public static byte[] decodeDERSM2Cipher(byte[] derCipher)
+ {
+ Asn1Sequence ds = DerSequence.GetInstance(derCipher);
+ byte[] c1x = ((DerInteger)ds[0]).Value.ToByteArray();
+ byte[] c1y = ((DerInteger)ds[1]).Value.ToByteArray();
+ byte[] c3 = ((DerOctetString)ds[2]).GetOctets();
+ byte[] c2 = ((DerOctetString)ds[3]).GetOctets();
+
+ int pos = 0;
+ int cureLength = 32;
+ byte[] cipherText = new byte[1 + c2.Length + cureLength * 2 + c3.Length];
+
+ byte uncompressedFlag = 0x04;
+ cipherText[0] = uncompressedFlag;
+ pos += 1;
+
+ if (c1x.Length >= cureLength)
+ {
+ Buffer.BlockCopy(c1x, c1x.Length - cureLength, cipherText, pos, cureLength);
+ }
+ else
+ {
+ Buffer.BlockCopy(c1x, 0, cipherText, pos + cureLength - c1x.Length, c1x.Length);
+ }
+ pos += cureLength;
+
+ if (c1y.Length >= cureLength)
+ {
+ Buffer.BlockCopy(c1y, c1y.Length - cureLength, cipherText, pos, cureLength);
+ }
+ else
+ {
+ Buffer.BlockCopy(c1y, 0, cipherText, pos + cureLength - c1y.Length, c1y.Length);
+ }
+ pos += cureLength;
+
+ Buffer.BlockCopy(c2, 0, cipherText, pos, c2.Length);
+ pos += c2.Length;
+
+ Buffer.BlockCopy(c3, 0, cipherText, pos, c3.Length);
+
+ return cipherText;
+ }
+
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM2Util.cs.meta b/Assets/Scripts/SecretUtils/Crypto/SM2Util.cs.meta
new file mode 100644
index 0000000..c970219
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM2Util.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a5759ff97d43f954ca6aa2cebce1d065
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM3Util.cs b/Assets/Scripts/SecretUtils/Crypto/SM3Util.cs
new file mode 100644
index 0000000..024ff35
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM3Util.cs
@@ -0,0 +1,48 @@
+using System;
+using Org.BouncyCastle.Crypto.Digests;
+
+namespace SecretUtils.Crypto
+{
+ /**
+ * 计算sm3 hash值
+ *
若无特殊说明,接口接收的都是原始的二进制数据,被hex或者base64编码的数据,务必解码之后再传进来
+ * @author liangruxing
+ *
+ */
+ class SM3Util
+ {
+ /**
+ * 计算hash值,在数据量不大时使用,数据量大应使用原生接口,分段计算sm3值
+ * @param srcData 待计算hash值的数据
+ * @return
+ */
+ public static byte[] Hash(byte[] srcData)
+ {
+ SM3Digest digest = new SM3Digest();
+ digest.BlockUpdate(srcData, 0, srcData.Length);
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+ return hash;
+ }
+
+ /**
+ * 校验sm3值,在数据量不大时使用,数据量大应使用原生接口,分段计算sm3值,然后校验
+ * @param srcData 待验证的数据
+ * @param sm3Hash 待验证的hash值
+ * @return
+ */
+ public static Boolean VerifyHash(byte[] srcData, byte[] sm3Hash)
+ {
+ byte[] newHash = Hash(srcData);
+ if (newHash.Length != sm3Hash.Length) {
+ return false;
+ }
+ for (int i = 0;i< newHash.Length;i++) {
+ if (newHash[i] != sm3Hash[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM3Util.cs.meta b/Assets/Scripts/SecretUtils/Crypto/SM3Util.cs.meta
new file mode 100644
index 0000000..4bea7aa
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM3Util.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5ac827b8946c6444b852c6b251ed00d1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM4Util.cs b/Assets/Scripts/SecretUtils/Crypto/SM4Util.cs
new file mode 100644
index 0000000..173da64
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM4Util.cs
@@ -0,0 +1,274 @@
+using System;
+using Org.BouncyCastle.Crypto;
+using Org.BouncyCastle.Crypto.Engines;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Security;
+using Org.BouncyCastle.Utilities.Encoders;
+
+namespace SecretUtils.Crypto
+{
+ /**
+ * sm4加解密工具类
+ *
因为数据加解密都是对字节数据加解密,因此需要注意加密前和解密后使用的字符集保持一致
+ *
若无特殊说明,接口接收的都是原始的二进制数据,被hex或者base64编码的数据,务必解码之后再传入接口
+ * @author liangruxing
+ *
+ */
+ internal class SM4Util
+ {
+ private const int SM4_ENCRYPT = 1;
+ private const int SM4_DECRYPT = 0;
+ public const int SM4_PKCS8PADDING = 1;
+ public const int SM4_NOPADDING = 0;
+ public const int SM4_KEY_128 = 128;
+
+ private const String iv = "DB4433CBE745731BBFA534109636F5FD";
+ ///
+ /// 使用国密SM4对文本加密字符串
+ ///
+ ///
+ ///
+ ///
+ public static string SM4EncryptData(string key, byte[] dataBytes)
+ {
+
+ //byte[] dataBytes = Encoding.UTF8.GetBytes(data);
+ byte[] cipher = SM4Util.EncryptCBC(dataBytes, Hex.Decode(key), Hex.Decode(key));
+ return Convert.ToBase64String(cipher);
+ }
+
+ public static string SM4DecryptData(string key,string data)
+ {
+ byte[] cipher = Convert.FromBase64String(data);
+ byte[] plain = SM4Util.DecryptCBC(cipher, Hex.Decode(key), Hex.Decode(key));
+ return Hex.ToHexString(cipher, 0, cipher.Length);
+ }
+
+ /**
+ * 生成sm4密钥,长度使用
+ * @param keySize 密钥位数(通过SM4Util的常量获取长度值)
+ * @return sm4密钥
+ */
+ public static byte[] GenerateKey(int keySize)
+ {
+ byte[] key = new byte[keySize / 8];
+ SecureRandom sr = new SecureRandom();
+ sr.NextBytes(key);
+
+ return key;
+ }
+
+ /**
+ * sm4 ecb模式加密数据,数据长度非16倍数,则使用默认PKCS8PADDING方式填充
+ * @param data 待加密的数据
+ * @param key sm4密钥
+ * @return 密文数据
+ */
+ public static byte[] EncryptECB(byte[] data, byte[] key)
+ {
+ return EncryptECB(data, key, SM4_PKCS8PADDING);
+ }
+
+ /**
+ * sm4 ecb模式解密数据,使用默认PKCS8PADDING方式去除填充
+ * @param cipher 密文数据
+ * @param key sm4密钥
+ * @return 明文字节数据
+ */
+ public static byte[] DecryptECB(byte[] cipher, byte[] key)
+ {
+ return DecryptECB(cipher, key, SM4_PKCS8PADDING);
+ }
+
+ /**
+ * sm4 CBC模式加密数据,数据长度非16倍数,则使用默认PKCS8PADDING方式填充
+ * @param data 待加密数据
+ * @param key sm4密钥
+ * @param iv 向量
+ * @return 密文数据
+ */
+ public static byte[] EncryptCBC(byte[] data, byte[] key, byte[] iv)
+ {
+ return EncryptCBC(data, key, iv, SM4_PKCS8PADDING);
+ }
+
+ /**
+ * sm4 cbc模式解密数据,使用默认PKCS8PADDING方式去除填充
+ * @param cipher sm4密文数据
+ * @param key sm4密钥
+ * @param iv 向量
+ * @return 明文字节数据
+ */
+ public static byte[] DecryptCBC(byte[] cipher, byte[] key, byte[] iv)
+ {
+ return DecryptCBC(cipher, key, iv, SM4_PKCS8PADDING);
+ }
+
+
+
+
+ /**
+ * sm4 ecb模式加密数据
+ * @param data 待加密数据
+ * @param key sm4密钥
+ * @param paddingMode 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充
+ * @return 返回密文数据
+ */
+ public static byte[] EncryptECB(byte[] data, byte[] key, int paddingMode)
+ {
+ IBlockCipher engine = new SM4Engine();
+ engine.Init(true, new KeyParameter(key));
+ if (paddingMode == SM4_PKCS8PADDING)
+ {
+ data = padding(data, SM4_ENCRYPT);
+ }
+ else
+ {
+ data = (byte [])data.Clone();
+ }
+ int length = data.Length;
+ for (int i = 0; length > 0; length -= 16, i += 16)
+ {
+ engine.ProcessBlock(data, i, data, i);
+ }
+ return data;
+ }
+
+ /**
+ * sm4 ecb模式解密数据
+ * @param cipher 密文数据
+ * @param key sm4密钥
+ * @param paddingMode 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充
+ * @return 返回明文字节数据
+ */
+ public static byte[] DecryptECB(byte[] cipher, byte[] key, int paddingMode)
+ {
+ IBlockCipher engine = new SM4Engine();
+ engine.Init(false, new KeyParameter(key));
+ int length = cipher.Length;
+ byte[] tmp = new byte[cipher.Length];
+ for (int i = 0; length > 0; length -= 16, i += 16)
+ {
+ engine.ProcessBlock(cipher, i, tmp, i);
+ }
+ byte[] plain = null;
+ if (paddingMode == SM4_PKCS8PADDING)
+ {
+ plain = padding(tmp, SM4_DECRYPT);
+ }
+ else
+ {
+ plain = tmp;
+ }
+ return plain;
+ }
+
+ /**
+ * CBC模式加密数据
+ * @param data 待加密数据
+ * @param key 密钥
+ * @param iv 向量
+ * @param paddingMode 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充
+ * @return 返回密文值
+ */
+ public static byte[] EncryptCBC(byte[] data, byte[] key, byte[] iv, int paddingMode)
+ {
+ IBlockCipher engine = new SM4Engine();
+ engine.Init(true, new KeyParameter(key));
+ if (paddingMode == SM4_PKCS8PADDING)
+ {
+ data = padding(data, SM4_ENCRYPT);
+ }
+ else
+ {
+ data = (byte [])data.Clone();
+ }
+ int length = data.Length;
+ iv = (byte [])iv.Clone();
+ for (int i = 0; length > 0; length -= 16, i += 16)
+ {
+
+ for (int j = 0; j < 16; j++)
+ {
+ data[i + j] = ((byte)(data[i + j] ^ iv[j]));
+ }
+ engine.ProcessBlock(data, i, data, i);
+ Buffer.BlockCopy(data, i, iv, 0, 16);
+ }
+ return data;
+ }
+
+ /**
+ * CBC模式解密数据
+ * @param cipher 密文数据
+ * @param key 密钥
+ * @param iv 向量
+ * @param isPadding 填充模式,具体支持请看类的常量字段,若使用不支持的模式则会默认无填充
+ * @return 返回明文字节数据
+ */
+ public static byte[] DecryptCBC(byte[] cipher, byte[] key, byte[] iv, int paddingMode)
+ {
+ IBlockCipher engine = new SM4Engine();
+ engine.Init(false, new KeyParameter(key));
+ int length = cipher.Length;
+ byte[] plain = new byte[cipher.Length];
+ iv = (byte [])iv.Clone();
+ for (int i = 0; length > 0; length -= 16, i += 16)
+ {
+
+ engine.ProcessBlock(cipher, i, plain, i);
+ for (int j = 0; j < 16; j++)
+ {
+ plain[j + i] = ((byte)(plain[i + j] ^ iv[j]));
+ }
+ Buffer.BlockCopy(cipher, i, iv, 0, 16);
+ }
+
+ byte[] res = null;
+ if (paddingMode == SM4_PKCS8PADDING)
+ {
+ res = padding(plain, SM4_DECRYPT);
+ }
+ else
+ {
+ res = plain;
+ }
+ return res;
+ }
+
+
+
+ /**
+ * PKCS8PADDING标准填充
+ * @param input 输入数据
+ * @param mode 填充或去除填充
+ * @return
+ */
+ private static byte[] padding(byte[] input, int mode)
+ {
+ if (input == null)
+ {
+ return null;
+ }
+
+ byte[] ret = (byte[])null;
+ if (mode == SM4_ENCRYPT)
+ {
+ int p = 16 - input.Length % 16;
+ ret = new byte[input.Length + p];
+ Buffer.BlockCopy(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];
+ Buffer.BlockCopy(input, 0, ret, 0, input.Length - p);
+ }
+ return ret;
+ }
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Crypto/SM4Util.cs.meta b/Assets/Scripts/SecretUtils/Crypto/SM4Util.cs.meta
new file mode 100644
index 0000000..3b7acfe
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Crypto/SM4Util.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 138d936349dd9b049a507ac143288134
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/SecretUtils.csproj b/Assets/Scripts/SecretUtils/SecretUtils.csproj
new file mode 100644
index 0000000..5e103ba
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/SecretUtils.csproj
@@ -0,0 +1,11 @@
+
+
+
+ netstandard2.0
+
+
+
+
+
+
+
diff --git a/Assets/Scripts/SecretUtils/SecretUtils.csproj.meta b/Assets/Scripts/SecretUtils/SecretUtils.csproj.meta
new file mode 100644
index 0000000..38c35d3
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/SecretUtils.csproj.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 6d089b637e647e44ea68ffccdf6bf2ec
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Sm2Base.cs b/Assets/Scripts/SecretUtils/Sm2Base.cs
new file mode 100644
index 0000000..15801b1
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Sm2Base.cs
@@ -0,0 +1,132 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using Org.BouncyCastle.Utilities.Encoders;
+using SecretUtils.Crypto;
+
+namespace SecretUtils
+{
+ public class Sm2Base
+ {
+ ///
+ /// 生成SM2 byte Key
+ ///
+ ///
+ public static SM2KeyPair GenerateKey()
+ {
+ SM2KeyPair keys = SM2Util.GenerateKeyPair();
+ return keys;
+ }
+ ///
+ /// 生成SM2 string Key
+ ///
+ ///
+ public static SM2KeyPairString GenerateKeyString()
+ {
+ return new SM2KeyPairString(SM2Util.GenerateKeyPair());
+ }
+ ///
+ /// 加密
+ ///
+ /// 公钥
+ /// 数据
+ ///
+ public static byte[] Encrypt(string pubkey, byte[] data)
+ {
+ byte[] cipher = SM2Util.Encrypt(Hex.Decode(pubkey), data);
+ return cipher;
+ }
+ public static byte[] Encrypt(byte[] pubkey, byte[] data)
+ {
+ byte[] cipher = SM2Util.Encrypt(pubkey, data);
+ return cipher;
+ }
+ ///
+ /// 解密
+ ///
+ /// 私钥
+ /// 数据
+ ///
+ public static byte[] Decrypt(string privkey, byte[] data)
+ {
+ byte[] plain = SM2Util.Decrypt(Hex.Decode(privkey), data);
+ return plain;
+ }
+ public static byte[] Decrypt(byte[] privkey, byte[] data)
+ {
+ byte[] plain = SM2Util.Decrypt(privkey, data);
+ return plain;
+ }
+ ///
+ /// 签名
+ ///
+ ///
+ public static byte[] Sign(byte[] privateKey, byte[] data)
+ {
+ byte[] signByte= SM2Util.Sign(privateKey, data);
+ return signByte;
+ }
+
+ public static byte[] Sign(string privateKey, byte[] data)
+ {
+ byte[] signByte = SM2Util.Sign(Hex.Decode(privateKey), data);
+ return signByte;
+ }
+ ///
+ /// 验签
+ ///
+ ///
+ public static bool VerifySign(byte[] publicKey, byte[] data, byte[] signData)
+ {
+ bool b= SM2Util.VerifySign(publicKey, data, signData);
+ return b;
+ }
+ public static bool VerifySign(string publicKey, byte[] data, byte[] signData)
+ {
+ bool b = SM2Util.VerifySign(Hex.Decode(publicKey), data, signData);
+ return b;
+ }
+ ///
+ /// 秘钥文件生成
+ ///
+ ///
+ ///
+ public static void GenerateKeyFile(byte[] keyData,string path)
+ {
+ FileStream fs = new FileStream(path, FileMode.Create);
+ BinaryWriter bw = new BinaryWriter(fs);
+ bw.Write(keyData);
+ bw.Close();
+ fs.Close();
+ }
+ public static void GenerateKeyFile(string keyData, string path)
+ {
+ byte[] keyBytes = Hex.Decode(keyData);
+ FileStream fs = new FileStream(path, FileMode.Create);
+ BinaryWriter bw = new BinaryWriter(fs);
+ bw.Write(keyBytes);
+ bw.Close();
+ fs.Close();
+ }
+ ///
+ /// 秘钥加载读取
+ ///
+ ///
+ ///
+ public static byte[] LoadKeyFileBytes(string filePath)
+ {
+ FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
+ byte[] buffur = new byte[fs.Length];
+ fs.Read(buffur, 0, (int)fs.Length);
+ return buffur;
+ }
+ public static string LoadKeyFileString(string filePath)
+ {
+ FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
+ byte[] buffur = new byte[fs.Length];
+ fs.Read(buffur, 0, (int)fs.Length);
+ return Hex.ToHexString(buffur);
+ }
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Sm2Base.cs.meta b/Assets/Scripts/SecretUtils/Sm2Base.cs.meta
new file mode 100644
index 0000000..ed52656
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Sm2Base.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 23687e8fc5cd7b848a643c306cd47eb4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Scripts/SecretUtils/Sm4Base.cs b/Assets/Scripts/SecretUtils/Sm4Base.cs
new file mode 100644
index 0000000..4d4945a
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Sm4Base.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Org.BouncyCastle.Crypto.Engines;
+using Org.BouncyCastle.Crypto.Paddings;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Utilities.Encoders;
+using SecretUtils.Crypto;
+
+namespace SecretUtils
+{
+ public class Sm4Base
+ {
+ ///
+ /// 生成SM4 byte Key
+ ///
+ ///
+ public static byte[] GenerateKey()
+ {
+ byte[] sm4key= SM4Util.GenerateKey(SM4Util.SM4_KEY_128);
+ return sm4key;
+ }
+ ///
+ /// 生成SM4 string Key
+ ///
+ ///
+ public static string GenerateKeyString()
+ {
+ byte[] sm4key = SM4Util.GenerateKey(SM4Util.SM4_KEY_128);
+
+ return Hex.ToHexString(sm4key, 0, sm4key.Length);
+ }
+
+ ///
+ /// CBC模式加密
+ ///
+ ///
+ ///
+ ///
+ public static byte[] EncryptCBC(byte[] data,string key)
+ {
+ byte[] cipher = SM4Util.EncryptCBC(data, Hex.Decode(key), Hex.Decode(key));
+ return cipher;
+ }
+ ///
+ /// CBC模式解密
+ ///
+ ///
+ ///
+ ///
+ public static byte[] DecryptCBC(byte[] data,string key)
+ {
+ byte[] plain = SM4Util.DecryptCBC(data, Hex.Decode(key), Hex.Decode(key));
+ return plain;
+ }
+
+
+ ///
+ /// ECB模式加密
+ ///
+ ///
+ ///
+ ///
+ public static byte[] EncryptECB(byte[] data, byte[] key)
+ {
+ byte[] cipher = SM4Util.EncryptECB(data, key);
+ return cipher;
+ }
+ ///
+ /// ECB模式解密
+ ///
+ ///
+ ///
+ ///
+ public static byte[] DecryptECB(byte[] data, byte[] key)
+ {
+ byte[] plain = SM4Util.DecryptECB(data, key);
+ return plain;
+ }
+ }
+}
diff --git a/Assets/Scripts/SecretUtils/Sm4Base.cs.meta b/Assets/Scripts/SecretUtils/Sm4Base.cs.meta
new file mode 100644
index 0000000..d1e0c10
--- /dev/null
+++ b/Assets/Scripts/SecretUtils/Sm4Base.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1e48668398500d549934d4c97bd762cf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Template/Scripts/Project/Manager/NetManager.cs b/Assets/Template/Scripts/Project/Manager/NetManager.cs
index c53406f..18007af 100644
--- a/Assets/Template/Scripts/Project/Manager/NetManager.cs
+++ b/Assets/Template/Scripts/Project/Manager/NetManager.cs
@@ -1,21 +1,18 @@
-using System.IO;
-using UnityEngine;
-using UnityEngine.Events;
+using Cysharp.Threading.Tasks;
using LitJson;
using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using Org.BouncyCastle.Utilities.Encoders;
+using SecretUtils;
using System;
using System.Collections;
using System.Collections.Generic;
-using UnityEditor;
-using UnityEngine.Networking;
-using Unity.VisualScripting.FullSerializer;
-using System.Runtime.InteropServices.ComTypes;
+using System.IO;
using System.Text;
-using UnityEngine.Networking.Types;
-using Unity.VisualScripting;
-using Newtonsoft.Json.Linq;
-using Cysharp.Threading.Tasks;
using System.Text.RegularExpressions;
+using UnityEngine;
+using UnityEngine.Events;
+using UnityEngine.Networking;
public class NetManager : BaseManager
{
@@ -56,7 +53,9 @@ public class NetManager : BaseManager
#if UNITY_EDITOR
Debug.Log("async req : " + getRequest.downloadHandler.text);
#endif
- T result = JsonConvert.DeserializeObject(getRequest.downloadHandler.text);
+ //T result = JsonConvert.DeserializeObject(getRequest.downloadHandler.text);
+ var s = Encrypt.DecryptECB(getRequest.downloadHandler.text);
+ T result = JsonConvert.DeserializeObject(s);
getRequest.Dispose();
return result;
}
@@ -140,7 +139,6 @@ public class NetManager : BaseManager
{
// 查找 & 的位置
int ampersandIndex = input.IndexOf('&');
-
// 如果没有 & 或者 & 后面没有 /,直接返回原字符串
if (ampersandIndex == -1 || ampersandIndex + 1 >= input.Length || input[ampersandIndex + 1] != '/')
{
@@ -198,8 +196,8 @@ public class NetManager : BaseManager
url += "machineId=" + GameManager.NetMgr.machineId + "&";
url += "batchId=" + GameManager.NetMgr.batchId + "&";
url += "courseId=" + GameManager.NetMgr.schemeID;
- DoStartCoroutine?.Invoke(GameManager.NetMgr.sendGet(url, backHandler));
- //DoStartCoroutine?.Invoke(GameManager.NetMgr.sendPost("member/pro/simulationStepRecord/getNewRecord", jsonData, backHandler1, "GET"));//发起请求
+
+ DoStartCoroutine?.Invoke(GameManager.NetMgr.sendGet(url, backHandler));//发起请求
}
private void backHandler(string text)
{
@@ -243,7 +241,32 @@ public class NetManager : BaseManager
setTime();
jsonData["remark"] = GameManager.NetMgr.sendSerData.remark;//备注
- DoStartCoroutine?.Invoke(GameManager.NetMgr.sendPost("member/pro/simulationStepRecord/add", jsonData, null));
+ //DoStartCoroutine?.Invoke(GameManager.NetMgr.sendPost("member/pro/simulationStepRecord/add", jsonData, null));
+
+ var _post_json = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(jsonData.ToJson()), Encrypt._key);
+ var _header = Encrypt.Header(GameManager.NetMgr.token);
+ DoStartCoroutine?.Invoke(PostRequest(url + "member/pro/simulationStepRecord/add", Hex.ToHexString(_post_json), _header, result =>
+ {
+ try
+ {
+ result = Encrypt.DecryptECB(result);
+ Debug.Log(result);
+ JObject jo = JObject.Parse(result);
+ if (jo["code"].ToObject() == 200)
+ {
+ //TipPanel.ShowTip("上传分数成功");
+ }
+ else
+ {
+ //TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString());
+ }
+ }
+ catch (Exception e)
+ {
+ Debug.Log($"{e.Message}\n ResultJosn:{result}");
+ }
+
+ }));
}
public void setTime()
{
@@ -290,17 +313,30 @@ public class NetManager : BaseManager
jsonData["testPoint"] = "";
jsonData["defaultScore"] = "";
- DoStartCoroutine?.Invoke(sendPost(webURLDic["练习学习"], jsonData, result =>
+ var _post_json = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(jsonData.ToJson()), Encrypt._key);
+ var _header = Encrypt.Header(GameManager.NetMgr.token);
+
+ DoStartCoroutine?.Invoke(PostRequest(url + webURLDic["练习学习"], Hex.ToHexString(_post_json), _header, result =>
{
- JObject jo = JObject.Parse(result);
- if (jo["code"].ToObject() == 200)
+ try
{
- //TipPanel.ShowTip("上传分数成功");
+ result = Encrypt.DecryptECB(result);
+ Debug.Log(result);
+ JObject jo = JObject.Parse(result);
+ if (jo["code"].ToObject() == 200)
+ {
+ //TipPanel.ShowTip("上传分数成功");
+ }
+ else
+ {
+ //TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString());
+ }
}
- else
+ catch (Exception e)
{
- //TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString());
+ Debug.Log($"{e.Message}\n ResultJosn:{result}");
}
+
}));
}
@@ -353,97 +389,6 @@ public class NetManager : BaseManager
}
}
-
- ///
- /// 获取本地配置文件
- ///
- ///
- /*public void GetConfig(UnityAction action)
- {
- string path = Application.streamingAssetsPath + "/info.ini";
- if (File.Exists(path))
- {
- try//HQB 1127
- {
- string str = File.ReadAllText(path);
- string text = str.Split("cdzxcjc://")[1].Split("\'|")[0];
- string[] arr = text.Split('&');
- //appld = arr[0];
- examId = arr[0];//试卷id
- examinationId = arr[1];//考场id
- stuId = arr[2];//用户id
- groupId = arr[3];//所在分组id
- operationType = arr[4];//用户操作类型
- batchId = arr[5];//学习批次id
- token = arr[6];
- url = arr[7];
- //action?.Invoke(true);
- string pathJson = Application.streamingAssetsPath + "/Config/Config.txt";
- if (File.Exists(pathJson))
- {
- string json = File.ReadAllText(pathJson);
- stepStrArr = json.Split('@');
- //sendSerData.recordContent = json;
- Debug.LogError(json);
- action?.Invoke(true);
- }
- else
- {
- Debug.Log("没有对应的文件Config/Config.txt");
- action?.Invoke(false);
- //UIManager.Instance.ShowPanel(E_UI_Layer.System, (panel) =>
- //{
- // panel.Init("没有读取到正确的Ip地址文件,请检查项目StreamingAssets文件夹下Config文件是否正常配置地址端口后再试!", E_MessageType.Error, Const.E_QuitApp);
- //});
- }
- }
- catch (Exception e)
- {
- Debug.Log("HQB——读取失败,先读默认info");
- string path2 = Application.streamingAssetsPath + "/info_1.ini";
- if (File.Exists(path2))
- {
- string str = File.ReadAllText(path2);
- string text = str.Split("cdzxcjc://")[1].Split("\'|")[0];
- string[] arr = text.Split('&');
- //appld = arr[0];
- examId = arr[0];//试卷id
- examinationId = arr[1];//考场id
- stuId = arr[2];//用户id
- groupId = arr[3];//所在分组id
- operationType = arr[4];//用户操作类型
- batchId = arr[5];//学习批次id
- token = arr[6];
- url = arr[7];
- string pathJson = Application.streamingAssetsPath + "/Config/Config.txt";
- if (File.Exists(pathJson))
- {
- string json = File.ReadAllText(pathJson);
- stepStrArr = json.Split('@');
- //sendSerData.recordContent = json;
- Debug.LogError(json);
- action?.Invoke(true);
- }
- else
- {
- Debug.Log("二次读取失败——HQB");
- action?.Invoke(false);
- }
- }
- }
- }
- else
- {
- Debug.Log("没有对应的文件info.ini");
- action?.Invoke(false);
- //UIManager.Instance.ShowPanel(E_UI_Layer.System, (panel) =>
- //{
- // panel.Init("没有读取到正确的Ip地址文件,请检查项目StreamingAssets文件夹下Config文件是否正常配置地址端口后再试!", E_MessageType.Error, Const.E_QuitApp);
- //});
- }
-
- }*/
-
public async void GetConfig(UnityAction action)
{
string path = Application.streamingAssetsPath + "/info.ini";
@@ -530,6 +475,38 @@ public class NetManager : BaseManager
Debug.Log(path);
File.WriteAllText(path, info);
}
+
+ public IEnumerator PostRequest(string _url, string _post_json, Dictionary _header = null, Action _callback = null)
+ {
+ using (UnityWebRequest request = new UnityWebRequest(_url, "POST"))
+ {
+ var data = Encoding.UTF8.GetBytes(_post_json);
+ request.uploadHandler = new UploadHandlerRaw(data);
+ request.downloadHandler = new DownloadHandlerBuffer();
+
+ if (_header != null)
+ {
+ foreach (var item in _header)
+ {
+ request.SetRequestHeader(item.Key, item.Value);
+ }
+ }
+
+ yield return request.SendWebRequest();
+ if (request.error != null)
+ {
+ Debug.Log(request.error);
+ _callback?.Invoke(null);
+ }
+ else
+ {
+ if (request.responseCode == 200)
+ {
+ _callback?.Invoke(request.downloadHandler.text);
+ }
+ }
+ }
+ }
}
public class Login
{