diff --git a/Assets/Plugins/BouncyCastle.Cryptography.dll b/Assets/Plugins/BouncyCastle.Cryptography.dll new file mode 100644 index 0000000..25a351b Binary files /dev/null and b/Assets/Plugins/BouncyCastle.Cryptography.dll differ diff --git a/Assets/Plugins/BouncyCastle.Cryptography.dll.meta b/Assets/Plugins/BouncyCastle.Cryptography.dll.meta new file mode 100644 index 0000000..7778d0d --- /dev/null +++ b/Assets/Plugins/BouncyCastle.Cryptography.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 400973bcd45da314f9becfd578db5293 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/SecretTest.meta b/Assets/Scripts/SecretTest.meta new file mode 100644 index 0000000..0d68448 --- /dev/null +++ b/Assets/Scripts/SecretTest.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 474c0b9fb61679a4882050ff5a4b3772 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/SecretTest/Encrypt.cs b/Assets/Scripts/SecretTest/Encrypt.cs new file mode 100644 index 0000000..0060b4a --- /dev/null +++ b/Assets/Scripts/SecretTest/Encrypt.cs @@ -0,0 +1,351 @@ +using LitJson; +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Paddings; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities.Encoders; +using SecretUtils; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Security.Policy; +using System.Text; +using UnityEngine; +using UnityEngine.Networking; + + +public class Encrypt : MonoBehaviour +{ + public static byte[] _key = Encoding.UTF8.GetBytes("1234567890abcdef"); + // Start is called before the first frame update + void Start() + { + + + } + + /// <summary> + /// Token 需获取 + /// Id 需获取 + /// </summary> + [ContextMenu("Get测试")] + public void SendGet() + { + var _cipher = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes("111"), _key); + + string id = Hex.ToHexString((Sm4Base.EncryptECB(Encoding.UTF8.GetBytes("111"), _key))); + var _query = Query(id); + var _header = Header("eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjdjYzM0YzU5LTQ2OTYtNDAzMS05YzI4LTNlMTE1MTFhYzRhNyJ9.MOGGhT80BvL3PMgmG1Vl46doUZpNLsbFQm6szg4c2IHQV2AwC3mnyfa2HzS1JJZp95i7ts3AR9YxTFqzKtqZXQ"); + + + StartCoroutine(GetRequest("http://172.16.1.127:8080/member/proSimulationExamination/queryById", _header, _query, + (x, y) => + { + if (!string.IsNullOrEmpty(y)) + { + Debug.Log(y); + Debug.Log(DecryptECB(y)); + } + })); + } + + /// <summary> + /// Token 需获取 + /// </summary> + [ContextMenu("Post测试")] + public void SendPost() + { + var _header = Header("eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImFkYjgwYjBkLTZlZDEtNDk3Ni04MDFhLTBjZjcwNTI5YzBmNiJ9.t3G2q9BbbsrMTZkBVfuSGcMQiWuqZHNkUBDcHsg-3qIG_6wqikIV-xL7xMl6bOciUWhF1xAdh6eBzpB6r3ZpyQ"); + MyData data = new MyData + { + id = "111", + appId = "", + courseId = "", + examId = "", + examinationId = "", + stuId = "", + groupId = "", + machineId = "", + batchId = "", + recordContent = "", + operationType = "", + isComp = "0", + currentProcess = "", + sumProcess = "", + score = "", + preScore = "", + inTimes = "1698723542", + remark = "", + stepName = "", + testPoint = "", + defaultScore = "" + }; + + //var _post_json = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(ToJson(data)), _key); + var _post_json = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes("{\"id\":\"\",\"appId\":\"10002\",\"courseId\":2002,\"examId\":\"336\",\"examinationId\":\"1309080392359215104\",\"stuId\":\"106\",\"groupId\":\"74\",\"machineId\":\"f9c243dcb8c896c581d42c85329e551a306bb648\",\"batchId\":\"1309168544625197056\",\"recordContent\":\"{\\\"time\\\":\\\"8.756936\\\",\\\"score\\\":0.0,\\\"stepList\\\":[{\\\"stepName\\\":\\\"\\u67E5\\u770B\\u4EFB\\u52A1\\u5355\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u70B9\\u51FB\\u79FB\\u52A8\\u4F5C\\u4E1A\\u7EC8\\u7AEF\\uFF0C\\u67E5\\u770B\\u60A8\\u63A5\\u53D7\\u5230\\u7684\\u4EFB\\u52A1\\u5DE5\\u5355\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":0.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u5DE5\\u4F5C\\u9884\\u7EA6\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u7535\\u8BDD\\u8054\\u7CFB\\u5BA2\\u6237\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":0.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u529E\\u7406\\u5DE5\\u4F5C\\u7968\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u9009\\u62E9\\u5408\\u9002\\u7684\\u5DE5\\u4F5C\\u7968\\uFF0C\\u5E76\\u6B63\\u786E\\u586B\\u5199\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u586B\\u5199\\u88C5\\u62C6\\u5DE5\\u5355\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u586B\\u5199\\u6B63\\u786E\\u7684\\u62C6\\u88C5\\u5DE5\\u4F5C\\u5355\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u6B63\\u786E\\u7740\\u88C5\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u524D\\u5F80\\u5DE5\\u5177\\u95F4\\uFF0C\\u9009\\u53D6\\u5DE5\\u4F5C\\u670D\\u3001\\u7EDD\\u7F18\\u978B\\u3001\\u5B89\\u5168\\u5E3D\\u3001\\u624B\\u5957\\uFF0C\\u5230\\u68B3\\u5986\\u955C\\u9762\\u524D\\u8FDB\\u884C\\u6362\\u88C5\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u9009\\u53D6\\u5DE5\\u5668\\u5177\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u524D\\u5F80\\u5DE5\\u5177\\u95F4\\uFF0C\\u6309\\u7167\\u987A\\u5E8F\\u9009\\u53D6\\u5265\\u7EBF\\u94B3,\\u7EDD\\u7F18\\u87BA\\u4E1D\\u5200,\\u9A8C\\u7535\\u7B14,\\u5DE5\\u4F5C\\u8BC1,\\u76D2\\u88C5\\u5C01\\u5370,\\u7EDD\\u7F18\\u80F6\\u5E26,\\u4E09\\u76F8\\u56DB\\u7EBF\\u8D39\\u63A7\\u667A\\u80FD\\u7535\\u80FD\\u8868\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u4E0E\\u5BA2\\u6237\\u6C9F\\u901A\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u524D\\u5F80\\u73B0\\u573A\\uFF0C\\u51FA\\u793A\\u5DE5\\u4F5C\\u724C\\uFF0C\\u544A\\u77E5\\u5DE5\\u4F5C\\u5185\\u5BB9\\u3002\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u73ED\\u524D\\u4F1A\\\",\\\"testPoint\\\":\\\"\\u6E05\\u524D\\u5F80\\u73B0\\u573A\\uFF0C\\u7531\\u5DE5\\u4F5C\\u8D1F\\u8D23\\u4EBA\\u68C0\\u67E5\\u7740\\u88C5\\u662F\\u5426\\u89C4\\u8303\\u3001\\u4E2A\\u4EBA\\u9632\\u62A4\\u7528\\u54C1\\u662F\\u5426\\u5408\\u683C\\u9F50\\u5907\\u3001\\u4EBA\\u5458\\u7CBE\\u795E\\u72B6\\u6001\\u662F\\u5426\\u826F\\u597D\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u4E09\\u6B65\\u9A8C\\u7535\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u8FDB\\u884C\\u4E09\\u6B65\\u9A8C\\u7535\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u63A5\\u7EBF\\u68C0\\u67E5\\u5E76\\u65AD\\u5F00\\u7535\\u6E90\\u9A8C\\u7535\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u65AD\\u5F00\\u7535\\u6E90\\u5E76\\u9A8C\\u7535\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u6838\\u5BF9\\u548C\\u6284\\u5F55\\u8BA1\\u91CF\\u8BBE\\u5907\\u4FE1\\u606F\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u70B9\\u51FB\\u6838\\u5BF9\\u7535\\u80FD\\u8868\\u94ED\\u724C\\u5185\\u5BB9\\u548C\\u6709\\u6548\\u68C0\\u9A8C\\u5408\\u683C\\u6807\\u5FD7\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":3.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u62C6\\u9664\\u7535\\u80FD\\u8BA1\\u91CF\\u88C5\\u7F6E\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u6309\\u8981\\u6C42\\u62C6\\u9664\\u7535\\u80FD\\u8BA1\\u91CF\\u88C5\\u7F6E\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":17.0,\\\"isKey\\\":true},{\\\"stepName\\\":\\\"\\u5B89\\u88C5\\u7535\\u80FD\\u8868\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u6309\\u8981\\u6C42\\u5B89\\u88C5\\u7535\\u80FD\\u8868\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":17.0,\\\"isKey\\\":true},{\\\"stepName\\\":\\\"\\u73B0\\u573A\\u901A\\u7535\\u53CA\\u68C0\\u67E5\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u6309\\u8981\\u6C42\\u8FDB\\u884C\\u901A\\u7535\\u53CA\\u68C0\\u67E5\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u5B9E\\u65BD\\u5C01\\u5370\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u5BF9\\u7535\\u80FD\\u8868\\u3001\\u8BA1\\u91CF\\u7BB1\\uFF08\\u67DC\\uFF09\\u52A0\\u5C01\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":3.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u6E05\\u7406\\u73B0\\u573A\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u628A\\u5DE5\\u5668\\u5177\\u6536\\u56DE\\u80CC\\u5305\\u5E76\\u6E05\\u7406\\u73B0\\u573A\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u73B0\\u573A\\u5B8C\\u5DE5\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u544A\\u77E5\\u5BA2\\u6237\\u5DF2\\u5B8C\\u5DE5\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u5DE5\\u4F5C\\u7968\\u7EC8\\u7ED3\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u529E\\u7406\\u5DE5\\u4F5C\\u7968\\u7EC8\\u7ED3\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false}]}\",\"operationType\":\"2\",\"isComp\":\"1\",\"currentProcess\":\"0\",\"sumProcess\":\"0\",\"score\":\"0,0,0,0,0,0,0,0\",\"preScore\":\"\",\"inTimes\":\"8.9035012\",\"remark\":null,\"stepName\":\"\",\"testPoint\":\"\",\"defaultScore\":\"\"}"), _key); + var ss = Hex.ToHexString(_post_json); + + + var mw = "c991b6107a1b8f97c32104da7debbbbd58e2bef0f865e08d10476ddacd40d4fbb82f0927a2e3ca051e16f1e32422c48bd7a630877f1155a2dc78781ab4792663bdbcb562038e6516d3f46d232329ccfccaf9c7df6918e99ec8578b82ceb808a07432ae1254949a4ee73f2e94616647911c141d85e38ecde0908d6ee5177ffdd9d7bf297d82427c946b5a5ce687237141dd7159f4d826b5d5d4e9b4e5538499a33eb772d4c44bc5cfe020e54c49d0c97cc17b422e250ec0e271ecc0261962428927783f2ab5b8c0a4f03be56d71cd3464c4c398e0a177b45061a3f32d2f24d563540ee36a88d7c8962c23c5f0dd76ae9ba5b962379ff5d1d311265eb547152138aae946184091f0830acfcb1ef81a46ab18e5af886521a957a4d4725622260b82f968e75dc55d3f359a0876c184add700928c1601b46b3dbc7dcba9a6977a664e3ddd0157609f97062c9bcbefc26a2882784ec98e63f20dd3dd24e4f0ce7ae16e0c20e752ac5656817e98823c3b28777d2f4598742ec26db176fff270a47cbf23b9b78470f4f90908b05f72ad248eb6380e4e2c593f6a947a92b60b26fda8d8d852c6c1a219064f47b13e26003e111969f2d1132930701f3d081090a752a81f289ee7017f95ce0cc31362d000f7c3486dcb59aff965d7b4675f0aca18c6570ad20a29095c39946496379b6ccf60aa43585c24806f96a86cd0d2108e1884da531c4e89cb43637f05da55eff2d47e1529b4b2b3acfa91af5f34b76d1be8ad06f7a5f07ef79b0b3da9942b766389981fcdbfa3ba9ae066d69e402f32f6cba6a813065c503081a9e7d32912660b2926af847a3eb96676596d98d3aff209ce359440f9fdf340982748de6a750982c92605acee45dc06027d2f9d2c51fd7d3438d3fd0763b79591815711ba1214b7fdc4426a287f1c115278f6caf8f249e0a3869a7e252619ea716be9b9832ea29599bdf620ef726fda5144533f57701fb5558db760e38660e1078e87ec8baf04e3326bf066115cea64f09a553e2d8f9af3b1235617a46e616c33f2394a778d4b1b2bbaac4b534f312fa5c704d10655f8fc5714ab8cf9d7c6d33f6af3a002433d444815d1dbac0c35c6d58bb340d61bbe51bab27bac0a7ddf17c19e9491e0243bc66ad76e3d62415465f644bfb377ee97ce63a8b237602744ab1017ca9a25fea505c1666099d5bf5c8e7cc915cb0f21c9af3544ef0dc9aef987ad10405147fca58520517ca2ec017cd904e9a8b4fe712ef827bf4a45121c50af09017cca977bd4853ee99a7a87b13306869806e5ecd577f099d9fa985f5fb74f36d04d81db868ac193bd64f182464fdd8dc9500ba6aed7f047eb14f46f5c503081a9e7d32912660b2926af847a1e7a594b01896afbac2f49bd078e92f0d57da44c392d6f47f98e124a20fdf26153bbea7bab7edfe24c04e7bfd9845a3b1d25353ee5ef9590fe662653f497ad8ddbc7e8648666e13f2b048d8ed5afcdc1aee959163c8498c6ef0ffb46214d6a05f30ef99daa097dabaff268f7cc7e7ca75f31e5ffbb020bac063c4a124947c96bad46a2ff3b8e8e94746e814719edfc792ececec041c046059e48c60905d8181b92a56ccbcd62bce327a25ad3ee82c2b40f22621d8b682629a56eeed2bb8e77f214c3946b390b07bd8b36d025002db8ee1a3a1b3f868c95c686ea87f8f222b4c7a9bd2ed869048e778873672bf17593313aaf074799132399d8ae3b15ad1341acb46031867e1a8c41ecb70766adfd774207cbd09ba7b879666a2e6f1ab05e85f0addf9548b74f4b41a87a3505aa9b9a74e88b414a3d387c175acc135f0048a736b7076c2b0f50b5591ee8b2056e7a8c7f2a91db3455d5725d9137ae50425e11fe38d752e2bde053f297f6b7322637f39596b74dd971ccdf16f798fbe6274f9ec14cd8eff1cff53264d348f10a3be48189cd42cb37199afb8ae6373593c8812a210ee89e75f0f3d696b94d844cc805dba3f91ed6abc4733e1718fafa3acf6510d24500b21c3d52e8f920685c439c9205322f9bad2bbfb8982b08fa25a982fbde476b34181a943939306b75becf8fe41ea171ac91f0dde410b6ff5ad1073d5e688d2ac677a8293e6bf2a55eecadc1ca04c0b64f002cd9e73b8a139582570fc0be972915fd3b87f1e467f63c86dfc21c068feb389f6a4672ac3b5a82b6540f50d13b55182322cdf31bac1d0b8b9874745abc68a5a505e5624dc5b546d26fa3adfa75c0c04e370f15c3466fd9bf65799fab4403bc954e4b985224e8a94b78138b9cb1f1799ad1b474fa478c5ef4ea442355bcb26de46a4b25f53275729ea6de2185839e8e0eabf3475e39e005c7fce01effa465e92be3b9b2c41969aab3e93f178198a4b3c69a74becfda7fd85df927201b93cc1dd35ff2181fe00b555c669524ed217f3f422d176c6f69e085542404a0d4a8875e9e93b1b88333031feace97a2aba5479c9e857142776de4daa3916dc8c86609c7db6fb62985cf2581df928e62a70c76fcb37c93bc9bd4b8c5fd6fda849a90cc896068ee92e3eb2ff040e45fe87b8d5535dcbea1799db4d075fdd864d27f4509d10ddbc8c2589097ad396cdbd7cd49c1f6aaa7f026819539f08b35865895b56aa53e45fb27ad390795c3169cb42d5e497c54cbef4adef47d892b50c191f979328f90d8bd724ab8c53a406f4e9c9cf4029fca0a5ca0c964ba7b99455b6b72412100d172af90575fec6382a6ce5e2bfe6b425cf3c2fe751872bf9d9a2f85ac88c5138171a6bad5944a9dbf5a49c57c8701578a130be8ad5ac229aa806e85ef2851b3468955e0fe4653090b9dbae13c4160cf85672864fec34008e81641fb84ecbdbe556730555d0b96cc7b981548a87c85d1618ba69aa1a3fa100afb217df99379e111a27c8e6ea695fae5656a8dc3cd2ba2bc38afc393e911751c2ec6fc198684b0f0015b7bc010db91ffed863db2fe5b6ea52a5cc5e8707d368dd5cdd87bdc0cdb49d84386fe06e03cf7654c78defed01e0dddea24e5382af4c54036a8ad4aad71fa9b7b0a2ecda09da47279d915bf777f0b5441d4763a2f00a78b5537776a20131a1a926d8bec035413fca2b11a2456466f4a963c0b9a4ddf359404984ee523cc993e06e1ef8ea9471b94b3a3e8824a8ca58091478b408b59a9813e080491b608fef8c59bb1cfd5c73b387aed59a9378ad521e82fe6715c418070d020c4a907dab095f67e8b4c5fda53e524f49c583f53a09da0281dd57bf82160cdf3a46de3e4b7854ec061201ab095ab7040a0c795f3582253dc9d51ede88c70c601903ca1c3c1a16103fd0a84b5d3d8f54c31ccb6094ee774418aa3a80821246f31d0f0d0194a4044a4f1d7118c7bc6423957c842df7cf8636349a178fff84412e5a7cc9ebe161cf1a9a0798057297f557df016eb69a026f3e212f6a31c887dbcdfe96a34eb63416e4d08d118cd4ba5cc84ec074ee095e88fc2ce7725a82e8007f2a07c853fe720c6638ac8097d534c9177f2b80a31d8d61a6841dbe5db3078dd7f101c6e9c1e0fd21fc11ddee8618c7afe36643e003c15fcb12fd13ebd75db97c26ccb41bd229a9f7ce06eda857d64cca37e4d0a29095c39946496379b6ccf60aa4358db345ff28c1e4d16a205357ce9c88bc84e89cb43637f05da55eff2d47e1529b4b2b3acfa91af5f34b76d1be8ad06f7a5671c6135ba06c79ef7167444ad4100ca55bca0e2f9d7da7374604188f4783ca7dbda6582d4d1e1080e0c651d138c82eea25a04347d6a4b58c2731977b9b6814a79663c279abb24e5ef25d34ca4639ce1e9786dd5e2ec572a5dd65d856a9e69c12e47350f3ea842ce89d06858021b88a3d7dcd99e26371dedabe1de0ae8e31adfb8c05c299ce1a30fc61a8e43d2df3cb863b79591815711ba1214b7fdc4426a280fe53205a0a902f90589513676e655432619ea716be9b9832ea29599bdf620ef726fda5144533f57701fb5558db760e3ba7c7348286cf9901e59e15f151ef1d6836416f66f7fdccd8f17d2efa3d7adddd827ef0869d0ffa999e3e0f60bedc7ce32e473888b39baa34227b8374c54267ea10a54c5886c3bbd5f731127787f6914408360906e83ba5fb74b331aac91ca12555c048d3ed91a99f3414f3c264485b32ac48b29d0bc7d2325444ba92b6f9d53d6df1d172703ee158ef6a8bc9f16b1ef45b3fe1d522fb77cafb14726e936bff79f6f9697be65eb345b9a056e01c580001d7314a25a5e3d7bbda08eb7425ca464589c16aa04a00f62b43376cae816bd963d74742ce3ca3c9339171cedfe8ec2c7376bffee608940411379209789dab7ae10995b826018acdb5c727dcbb9db2f753dfc653090873f5e7da778dbcabb3b5c3ddae0384f27d674fca8f4a04cd1ebaf83016f44cd90c58300a0a6266840158643943f0afa7e702ace9aec37d4643738319df610432a2ea97c0f9f70d4201ccf5b6ea52a5cc5e8707d368dd5cdd87bdca4313ccdbcdb2a767275c333312e51b3bd161d0bd96e31d55bd15c3764402df62f3846f61a1f118f2176fb9a75ac7fedbb77171c22d7b28f500f2404a073968bb796452df87d0b7480ede41bb101355542df7cf8636349a178fff84412e5a7ccbfa2bff2200fd611cfc07db74ee86a4ecdecf7e3ea2fee8421dc21b2540b612934eb63416e4d08d118cd4ba5cc84ec0771d6a9da82bc1fd9f36c30d468a26a5346796aa387265490ee3599f2b8b9b4c992a56ccbcd62bce327a25ad3ee82c2b4c5c76c03819583edd4d0705bc2742eaddecad2aa81124b139bd76f96a6dac185a22c75bf77c2ae288b5f1fb375c7658d2498569d1e03b1009cf08ae4e9ee13fa3b7bfbcaaac7769a5165400f7b502a5f8f5411f98e0a7b639708b3b702396b6256b1f4529fbaabf46b318d8ce833984bb846e196594732bcf56bee4f1278ac96c620953b21453746be10241b70414cbe63036522f42f5a4a188594ea2e564dcbeb7db30226bcbcc0dafdfba01f6f6c0a5b6ea52a5cc5e8707d368dd5cdd87bdca4313ccdbcdb2a767275c333312e51b348c1791d1a147f07f5a232ea6437e2335b2bbfbefbde9924579056060842b62eaf59e8f28d27a4d72afb7bcb7b243e979ae5236e8ab93e465b26671cd28cba89444fcbf9c4c3ac5185fec96cf851442c9fbe1c802b6d8b9ad0bb3d0eac0d6cf32cf2d3d2a193bff91417df2a5eecbac1a3b0f0d7220dbaef65767273ba96ef95630dc053430d9967593e4dac7c156c1654b100b05623fe36ec51f193f0c2f1a5382bdf9e53da8e7a1405ff8be6415da12ac48b29d0bc7d2325444ba92b6f9d53a1f665c904c4f1d3ca27dd6d341784ce88b3e4fa2eb7c65d60fe1420723689971992b99ff073422a4381ac7010881d7e4e85b242f642dd6b824ecbd7396688d9bf5c8e7cc915cb0f21c9af3544ef0dc99bdd85db278cacef96eedda64b74f90a017cd904e9a8b4fe712ef827bf4a45121c50af09017cca977bd4853ee99a7a87cc93935b8c92056c574cc4163791c11c0f59e26f46d9ebb47a1d8179914b0d115b6ea52a5cc5e8707d368dd5cdd87bdcbab8f7ac775b3c5a42acd41c1314094e6c2566d456640a3d101a216c68ce1d14c8f0c8231802a722944f27bd21d859489aff2ac8cc0c3c0a16adc9ab35170ce3f95f7de2e5cf60e10185a0a46381ecb0950081db8167781afda8c5339a05719476fcb37c93bc9bd4b8c5fd6fda849a90cc896068ee92e3eb2ff040e45fe87b8d5535dcbea1799db4d075fdd864d27f452942d872728d4752c35a9e9f9fe11c18d4ff5a89457256d9550b9efb5f5b167a6c409ff360ab92abf93fca03abb27a8524a2cc3fcba485e47a5a3e4d782ccd1b819a7027d6a770d33c31a3681dc2604f9e2ee76aa35a9325c82e7b034bbf3f79bfdbb2b912e33678a35992b9df0f001d3b7bfbcaaac7769a5165400f7b502a5fee511dd8111a11c0afec8f61939f0647088a6b89df35e207357cf5c45deddc0eb846e196594732bcf56bee4f1278ac96d92d84ed80daa1d82ef09a10aa9f371e6b585cd16e9a1500b280ab968e58e6afff52ca70e2d5ebb9f9575d2ea42726b3d9bf28567112d0dec6d275aca3f12faf1c1807643f7ec9ca5227c59a665d45bce05fc9351e24ed072412205e49acb6d42fd30e8b668fd1550d7e22d5f92e350e76fcb37c93bc9bd4b8c5fd6fda849a90cc896068ee92e3eb2ff040e45fe87b8db9f847717c402a87846a3808ea89a9d1130cd8ce7debcb5e519e44c44a8bc132000f264762c22afa5edfd0c58354c76f33631df602f452fcc82e5f82ea28b1d3a1c1888f9a1e3fbbb20ac9e05539731a8b05b284d4543801bbfa3ae7bdaced616a862174a12892c40739c0e0751d4331a130098ffb8194f849325eba23c9fb9675599f9dec264d2941c4bf1fe3cbc1592ef368fbac3dca171de0216dc9d4dc89aeb2a577cece6b26f16520b30354700a864655a60e0ce75346d72bfb29141a1d2962e6c4a7372b858f222210faf8e8869de724f5bdcd4ceacb9c7fc851a5198f"; + + Debug.Log($"密文:<color=red>{ss}</color>"); + Debug.Log($"解密:<color=red>{Encrypt.DecryptECB(ss)}</color>"); + StartCoroutine(PostRequest("http://172.16.1.127:8080/member/pro/simulationStepRecord/addSubmitDetail", mw, _header, + (x, y) => + { + if (!string.IsNullOrEmpty(y)) + { + Debug.Log(y); + Debug.Log(DecryptECB(y)); + } + })); + } + + [ContextMenu("Post测试222")] + public void SendPostwqewq() + { + StartCoroutine(sendPost("",null)); + } + + public IEnumerator sendPost(string itf, JsonData jsonData, Action<string> action=null) + { + //string ds = jsonData.ToJson(); + string ds = "{\"id\":\"\",\"appId\":\"10002\",\"courseId\":2002,\"examId\":\"336\",\"examinationId\":\"1309080392359215104\",\"stuId\":\"106\",\"groupId\":\"74\",\"machineId\":\"f9c243dcb8c896c581d42c85329e551a306bb648\",\"batchId\":\"1309168544625197056\",\"recordContent\":\"{\\\"time\\\":\\\"8.756936\\\",\\\"score\\\":0.0,\\\"stepList\\\":[{\\\"stepName\\\":\\\"\\u67E5\\u770B\\u4EFB\\u52A1\\u5355\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u70B9\\u51FB\\u79FB\\u52A8\\u4F5C\\u4E1A\\u7EC8\\u7AEF\\uFF0C\\u67E5\\u770B\\u60A8\\u63A5\\u53D7\\u5230\\u7684\\u4EFB\\u52A1\\u5DE5\\u5355\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":0.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u5DE5\\u4F5C\\u9884\\u7EA6\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u7535\\u8BDD\\u8054\\u7CFB\\u5BA2\\u6237\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":0.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u529E\\u7406\\u5DE5\\u4F5C\\u7968\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u9009\\u62E9\\u5408\\u9002\\u7684\\u5DE5\\u4F5C\\u7968\\uFF0C\\u5E76\\u6B63\\u786E\\u586B\\u5199\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u586B\\u5199\\u88C5\\u62C6\\u5DE5\\u5355\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u586B\\u5199\\u6B63\\u786E\\u7684\\u62C6\\u88C5\\u5DE5\\u4F5C\\u5355\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u6B63\\u786E\\u7740\\u88C5\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u524D\\u5F80\\u5DE5\\u5177\\u95F4\\uFF0C\\u9009\\u53D6\\u5DE5\\u4F5C\\u670D\\u3001\\u7EDD\\u7F18\\u978B\\u3001\\u5B89\\u5168\\u5E3D\\u3001\\u624B\\u5957\\uFF0C\\u5230\\u68B3\\u5986\\u955C\\u9762\\u524D\\u8FDB\\u884C\\u6362\\u88C5\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u9009\\u53D6\\u5DE5\\u5668\\u5177\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u524D\\u5F80\\u5DE5\\u5177\\u95F4\\uFF0C\\u6309\\u7167\\u987A\\u5E8F\\u9009\\u53D6\\u5265\\u7EBF\\u94B3,\\u7EDD\\u7F18\\u87BA\\u4E1D\\u5200,\\u9A8C\\u7535\\u7B14,\\u5DE5\\u4F5C\\u8BC1,\\u76D2\\u88C5\\u5C01\\u5370,\\u7EDD\\u7F18\\u80F6\\u5E26,\\u4E09\\u76F8\\u56DB\\u7EBF\\u8D39\\u63A7\\u667A\\u80FD\\u7535\\u80FD\\u8868\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u4E0E\\u5BA2\\u6237\\u6C9F\\u901A\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u524D\\u5F80\\u73B0\\u573A\\uFF0C\\u51FA\\u793A\\u5DE5\\u4F5C\\u724C\\uFF0C\\u544A\\u77E5\\u5DE5\\u4F5C\\u5185\\u5BB9\\u3002\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u73ED\\u524D\\u4F1A\\\",\\\"testPoint\\\":\\\"\\u6E05\\u524D\\u5F80\\u73B0\\u573A\\uFF0C\\u7531\\u5DE5\\u4F5C\\u8D1F\\u8D23\\u4EBA\\u68C0\\u67E5\\u7740\\u88C5\\u662F\\u5426\\u89C4\\u8303\\u3001\\u4E2A\\u4EBA\\u9632\\u62A4\\u7528\\u54C1\\u662F\\u5426\\u5408\\u683C\\u9F50\\u5907\\u3001\\u4EBA\\u5458\\u7CBE\\u795E\\u72B6\\u6001\\u662F\\u5426\\u826F\\u597D\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u4E09\\u6B65\\u9A8C\\u7535\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u8FDB\\u884C\\u4E09\\u6B65\\u9A8C\\u7535\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u63A5\\u7EBF\\u68C0\\u67E5\\u5E76\\u65AD\\u5F00\\u7535\\u6E90\\u9A8C\\u7535\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u65AD\\u5F00\\u7535\\u6E90\\u5E76\\u9A8C\\u7535\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u6838\\u5BF9\\u548C\\u6284\\u5F55\\u8BA1\\u91CF\\u8BBE\\u5907\\u4FE1\\u606F\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u70B9\\u51FB\\u6838\\u5BF9\\u7535\\u80FD\\u8868\\u94ED\\u724C\\u5185\\u5BB9\\u548C\\u6709\\u6548\\u68C0\\u9A8C\\u5408\\u683C\\u6807\\u5FD7\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":3.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u62C6\\u9664\\u7535\\u80FD\\u8BA1\\u91CF\\u88C5\\u7F6E\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u6309\\u8981\\u6C42\\u62C6\\u9664\\u7535\\u80FD\\u8BA1\\u91CF\\u88C5\\u7F6E\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":17.0,\\\"isKey\\\":true},{\\\"stepName\\\":\\\"\\u5B89\\u88C5\\u7535\\u80FD\\u8868\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u6309\\u8981\\u6C42\\u5B89\\u88C5\\u7535\\u80FD\\u8868\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":17.0,\\\"isKey\\\":true},{\\\"stepName\\\":\\\"\\u73B0\\u573A\\u901A\\u7535\\u53CA\\u68C0\\u67E5\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u6309\\u8981\\u6C42\\u8FDB\\u884C\\u901A\\u7535\\u53CA\\u68C0\\u67E5\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u5B9E\\u65BD\\u5C01\\u5370\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u5BF9\\u7535\\u80FD\\u8868\\u3001\\u8BA1\\u91CF\\u7BB1\\uFF08\\u67DC\\uFF09\\u52A0\\u5C01\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":3.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u6E05\\u7406\\u73B0\\u573A\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u628A\\u5DE5\\u5668\\u5177\\u6536\\u56DE\\u80CC\\u5305\\u5E76\\u6E05\\u7406\\u73B0\\u573A\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u73B0\\u573A\\u5B8C\\u5DE5\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u544A\\u77E5\\u5BA2\\u6237\\u5DF2\\u5B8C\\u5DE5\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false},{\\\"stepName\\\":\\\"\\u5DE5\\u4F5C\\u7968\\u7EC8\\u7ED3\\\",\\\"testPoint\\\":\\\"\\u8BF7\\u529E\\u7406\\u5DE5\\u4F5C\\u7968\\u7EC8\\u7ED3\\\",\\\"setScore\\\":0.0,\\\"defaultScore\\\":5.0,\\\"isKey\\\":false}]}\",\"operationType\":\"2\",\"isComp\":\"1\",\"currentProcess\":\"0\",\"sumProcess\":\"0\",\"score\":\"0,0,0,0,0,0,0,0\",\"preScore\":\"\",\"inTimes\":\"8.9035012\",\"remark\":null,\"stepName\":\"\",\"testPoint\":\"\",\"defaultScore\":\"\"}"; + var _post_json = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(ds), _key); + + var ss = Hex.ToHexString(_post_json); + Debug.Log($"密文:<color=red>{ss}</color>"); + Debug.Log($"解密:<color=red>{Encrypt.DecryptECB(ss)}</color>"); + + //byte[] postBytes = Encoding.Default.GetBytes(ds); + using (UnityWebRequest request = new UnityWebRequest("http://172.16.1.127:8080/member/pro/simulationStepRecord/addSubmitDetail", "POST")) + { + request.uploadHandler = new UploadHandlerRaw(_post_json); + request.downloadHandler = new DownloadHandlerBuffer(); + request.SetRequestHeader("Content-Type", "application/json"); + //if (GameManager.NetMgr.token != "") + { + request.SetRequestHeader("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImFkYjgwYjBkLTZlZDEtNDk3Ni04MDFhLTBjZjcwNTI5YzBmNiJ9.t3G2q9BbbsrMTZkBVfuSGcMQiWuqZHNkUBDcHsg-3qIG_6wqikIV-xL7xMl6bOciUWhF1xAdh6eBzpB6r3ZpyQ"); + } + yield return request.SendWebRequest();//发送请求 + if (request.responseCode == 200)//检验是否成功 + { + string text = request.downloadHandler.text; + var s = Encrypt.DecryptECB(text); + Debug.Log(s); + //action?.Invoke(text); + action?.Invoke(s); + } + else + { + Debug.Log("请求失败:" + request.responseCode); + } + }//method传输方式,默认为Get; + } + + // Update is called once per frame + void Update() + { + + } + + + public static string DecryptECB(string encryptedHex) + { + byte[] _key = Encoding.UTF8.GetBytes("1234567890abcdef"); + // 将16进制字符串转换为字节数组 + byte[] encryptedBytes = HexToBytes(encryptedHex); + + // 创建SM4引擎 + var engine = new SM4Engine(); + + // 使用ECB模式 + var cipher = new PaddedBufferedBlockCipher(engine, new Pkcs7Padding()); + + // 初始化解密器 + cipher.Init(false, new KeyParameter(_key)); + + // 解密 + byte[] decryptedBytes = new byte[cipher.GetOutputSize(encryptedBytes.Length)]; + int length = cipher.ProcessBytes(encryptedBytes, 0, encryptedBytes.Length, decryptedBytes, 0); + length += cipher.DoFinal(decryptedBytes, length); + + // 将解密后的字节数组转换为字符串 + string decryptedText = Encoding.UTF8.GetString(decryptedBytes, 0, length); + + return decryptedText; + } + + private static byte[] HexToBytes(string hex) + { + int length = hex.Length; + byte[] bytes = new byte[length / 2]; + for (int i = 0; i < length; i += 2) + { + bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); + } + return bytes; + } + + /// <summary> + /// Get请求 + /// </summary> + /// <param name="_url"></param> + /// <param name="_header"></param> + /// <param name="_query"></param> + /// <param name="_callback"></param> + /// <returns></returns> + public static IEnumerator GetRequest(string _url, Dictionary<string, string> _header = null, Dictionary<string, string> _query = null, Action<string, string> _callback = null) + { + //if (_url.EndsWith("/")) + //{ + // _url = _url.Substring(0, _url.Length - 1); + //} + + StringBuilder builder = new StringBuilder(); + builder.Append(_url); + + if (_query != null) + { + builder.Append("?"); + int i = 0; + foreach (var item in _query) + { + if (i > 0) + builder.Append("&"); + builder.AppendFormat("{0}={1}", item.Key, item.Value); + i++; + } + } + + using (UnityWebRequest request = UnityWebRequest.Get(builder.ToString())) + { + if (_header != null) + { + foreach (var item in _header) + { + request.SetRequestHeader(item.Key, item.Value); + } + } + + yield return request.SendWebRequest(); + + if (request.error != null) + { + _callback?.Invoke(request.error, null); + } + else + { + _callback?.Invoke(null, request.downloadHandler.text); + } + } + } + + /// <summary> + /// Post请求 + /// </summary> + /// <param name="_url"></param> + /// <param name="_post_json"></param> + /// <param name="_callback"></param> + /// <returns></returns> + public static IEnumerator PostRequest(string _url, string _post_json, Dictionary<string, string> _header = null, Action<string, string> _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) + { + _callback?.Invoke(request.error, null); + } + else + { + _callback?.Invoke(null, request.downloadHandler.text); + } + } + } + + public Dictionary<string, string> Query( + string id/*, string appId, string courseId, string examId, string examinationId, + string stuId, string groupId, string machineId, string batchId, string recordContent, + string operationType, string isComp, string currentProcess, string sumProcess, + string score, string preScore, string inTimes, string remark, string stepName, + string testPoint, string defaultScore*/) + { + Dictionary<string, string> request_querylist = new Dictionary<string, string>(); + request_querylist.Add("id", id); + //request_querylist.Add("appId", appId); + //request_querylist.Add("courseId", courseId); + //request_querylist.Add("examId", examId); + //request_querylist.Add("examinationId", examinationId); + //request_querylist.Add("stuId", stuId); + //request_querylist.Add("groupId", groupId); + //request_querylist.Add("machineId", machineId); + //request_querylist.Add("batchId", batchId); + //request_querylist.Add("recordContent", recordContent); + //request_querylist.Add("operationType", operationType); + //request_querylist.Add("isComp", isComp); + //request_querylist.Add("currentProcess", currentProcess); + //request_querylist.Add("sumProcess", sumProcess); + //request_querylist.Add("score", score); + //request_querylist.Add("preScore", preScore); + //request_querylist.Add("inTimes", inTimes); + //request_querylist.Add("remark", remark); + //request_querylist.Add("stepName", stepName); + //request_querylist.Add("testPoint", testPoint); + //request_querylist.Add("defaultScore", defaultScore); + return request_querylist; + } + + public static Dictionary<string, string> Header(string token) + { + Dictionary<string, string> request_header = new Dictionary<string, string>(); + request_header.Add("Content-Type", "application/json"); + request_header.Add("Authorization", token); + return request_header; + } + + public class MyData + { + public string id; + public string appId; + public string courseId; + public string examId; + public string examinationId; + public string stuId; + public string groupId; + public string machineId; + public string batchId; + public string recordContent; + public string operationType; + public string isComp; + public string currentProcess; + public string sumProcess; + public string score; + public string preScore; + public string inTimes; + public string remark; + public string stepName; + public string testPoint; + public string defaultScore; + } + public string ToJson(MyData data) + { + return JsonUtility.ToJson(data); + } + + public static MyData FromJson(string json) + { + return JsonUtility.FromJson<MyData>(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签名 + * <p>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验签 + * <p>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值 + * <p>若无特殊说明,接口接收的都是原始的二进制数据,被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加解密工具类 + * <p>因为数据加解密都是对字节数据加解密,因此需要注意加密前和解密后使用的字符集保持一致 + * <p>若无特殊说明,接口接收的都是原始的二进制数据,被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"; + /// <summary> + /// 使用国密SM4对文本加密字符串 + /// </summary> + /// <param name="key"></param> + /// <param name="data"></param> + /// <returns></returns> + 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 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>netstandard2.0</TargetFramework> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="BouncyCastle.NetCore" Version="1.8.6" /> + </ItemGroup> + +</Project> 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 + { + /// <summary> + /// 生成SM2 byte Key + /// </summary> + /// <returns></returns> + public static SM2KeyPair GenerateKey() + { + SM2KeyPair keys = SM2Util.GenerateKeyPair(); + return keys; + } + /// <summary> + /// 生成SM2 string Key + /// </summary> + /// <returns></returns> + public static SM2KeyPairString GenerateKeyString() + { + return new SM2KeyPairString(SM2Util.GenerateKeyPair()); + } + /// <summary> + /// 加密 + /// </summary> + /// <param name="pubkey">公钥</param> + /// <param name="data">数据</param> + /// <returns></returns> + 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; + } + /// <summary> + /// 解密 + /// </summary> + /// <param name="privkey">私钥</param> + /// <param name="data">数据</param> + /// <returns></returns> + 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; + } + /// <summary> + /// 签名 + /// </summary> + /// <returns></returns> + 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; + } + /// <summary> + /// 验签 + /// </summary> + /// <returns></returns> + 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; + } + /// <summary> + /// 秘钥文件生成 + /// </summary> + /// <param name="keyData"></param> + /// <param name="path"></param> + 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(); + } + /// <summary> + /// 秘钥加载读取 + /// </summary> + /// <param name="filePath"></param> + /// <returns></returns> + 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 + { + /// <summary> + /// 生成SM4 byte Key + /// </summary> + /// <returns></returns> + public static byte[] GenerateKey() + { + byte[] sm4key= SM4Util.GenerateKey(SM4Util.SM4_KEY_128); + return sm4key; + } + /// <summary> + /// 生成SM4 string Key + /// </summary> + /// <returns></returns> + public static string GenerateKeyString() + { + byte[] sm4key = SM4Util.GenerateKey(SM4Util.SM4_KEY_128); + + return Hex.ToHexString(sm4key, 0, sm4key.Length); + } + + /// <summary> + /// CBC模式加密 + /// </summary> + /// <param name="data"></param> + /// <param name="key"></param> + /// <returns></returns> + public static byte[] EncryptCBC(byte[] data,string key) + { + byte[] cipher = SM4Util.EncryptCBC(data, Hex.Decode(key), Hex.Decode(key)); + return cipher; + } + /// <summary> + /// CBC模式解密 + /// </summary> + /// <param name="data"></param> + /// <param name="key"></param> + /// <returns></returns> + public static byte[] DecryptCBC(byte[] data,string key) + { + byte[] plain = SM4Util.DecryptCBC(data, Hex.Decode(key), Hex.Decode(key)); + return plain; + } + + + /// <summary> + /// ECB模式加密 + /// </summary> + /// <param name="data"></param> + /// <param name="key"></param> + /// <returns></returns> + public static byte[] EncryptECB(byte[] data, byte[] key) + { + byte[] cipher = SM4Util.EncryptECB(data, key); + return cipher; + } + /// <summary> + /// ECB模式解密 + /// </summary> + /// <param name="data"></param> + /// <param name="key"></param> + /// <returns></returns> + 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 1acb89a..66c8bfb 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<NetManager> { @@ -56,7 +53,9 @@ public class NetManager : BaseManager<NetManager> #if UNITY_EDITOR Debug.Log("async req : " + getRequest.downloadHandler.text); #endif - T result = JsonConvert.DeserializeObject<T>(getRequest.downloadHandler.text); + //T result = JsonConvert.DeserializeObject<T>(getRequest.downloadHandler.text); + var s = Encrypt.DecryptECB(getRequest.downloadHandler.text); + T result = JsonConvert.DeserializeObject<T>(s); getRequest.Dispose(); return result; } @@ -198,8 +197,8 @@ public class NetManager : BaseManager<NetManager> 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 +242,32 @@ public class NetManager : BaseManager<NetManager> 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<int>() == 200) + { + //TipPanel.ShowTip("上传分数成功"); + } + else + { + //TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString()); + } + } + catch (Exception e) + { + Debug.Log($"<Color=red>{e.Message}\n ResultJosn:{result}</Color>"); + } + + })); } public void setTime() { @@ -290,18 +314,30 @@ public class NetManager : BaseManager<NetManager> 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 => { - Debug.Log("最终上传内容:" + result); - JObject jo = JObject.Parse(result); - if (jo["code"].ToObject<int>() == 200) + try { - TipPanel.ShowTip("上传分数成功"); + result = Encrypt.DecryptECB(result); + Debug.Log(result); + JObject jo = JObject.Parse(result); + if (jo["code"].ToObject<int>() == 200) + { + //TipPanel.ShowTip("上传分数成功"); + } + else + { + //TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString()); + } } - else + catch (Exception e) { - TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString()); + Debug.Log($"<Color=red>{e.Message}\n ResultJosn:{result}</Color>"); } + })); } @@ -354,97 +390,6 @@ public class NetManager : BaseManager<NetManager> } } - - /// <summary> - /// 获取本地配置文件 - /// </summary> - /// <param name="action"></param> - /*public void GetConfig(UnityAction<bool> 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<UI_MessagePanel>(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<UI_MessagePanel>(E_UI_Layer.System, (panel) => - //{ - // panel.Init("没有读取到正确的Ip地址文件,请检查项目StreamingAssets文件夹下Config文件是否正常配置地址端口后再试!", E_MessageType.Error, Const.E_QuitApp); - //}); - } - - }*/ - public async void GetConfig(UnityAction<bool> action) { string path = Application.streamingAssetsPath + "/info.ini"; @@ -530,6 +475,38 @@ public class NetManager : BaseManager<NetManager> string path = Application.streamingAssetsPath + "/start.ini"; File.WriteAllText(path, info); } + + public IEnumerator PostRequest(string _url, string _post_json, Dictionary<string, string> _header = null, Action<string> _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 {