Browse Source

拉卡拉加解密调试,通过

lcl 1 day ago
parent
commit
6b72af712a

+ 126 - 41
AppStart/Helper/PublicImportDataService.cs

@@ -16,6 +16,7 @@ using Org.BouncyCastle.Crypto;
 using Org.BouncyCastle.Math;
 using System.Net.Http;
 using System.Threading.Tasks;
+using System.IO;
 
 namespace MySystem
 {
@@ -1251,8 +1252,9 @@ namespace MySystem
         string lklClientId = "testsit";
         string lklClientSecret = "EguwEckByf2I6u6z";
         string lklReqUrl = "https://test.wsmsd.cn/sit";
-        string lklReqUrl2 = "https://test.wsmsd.cn/sit/htkmerchants/channel/customer/update/fee/";
-        string lklPriKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIo8rqIb543AJFGzWXMThtTKnqfQYxyP2zqUQ8sgRhGkEcIIel8ZnjbZIvAepD3NxTzyUxup+5J9C4mI+E0CoweCZPufaBh/Gi0vfXWXDWobYBElFIjJDegddLoYF72QVFYrwj+xVu5HF5X62hSz03YQ+Mp6q5jbyjGX34BTdTqBAgMBAAECgYAGgLmmlbVWJEn1F7CzVpGg+pXdbzKtYBlME3fPszFGoMsmz3kptnncSsk/ZlKbt22CCyR0lIHJi6U2e2VyUneep+vzSlvZdpdB4EgGZw3gLC7Cvz5bb9Uh3QJwBBoSHMdDBUnx/dYgnJhitCq/akH23LdyBpkYHx037W0EG+XaEQJBAMC9xgukaD2GsbRzspZeTWQToLh7K6Gz7o4VAg0r/ph2Lm/Z/jzjrahXzjcxSdwnMJmFJagDgFbmprZU5PWCMNECQQC3m25z/v3//TkkAzERV1Pjw/+d/h7Nd8I8G9wD9ZLGCO0JqMf+eugVXQ9dRyTC7xSuuV7EQAAMFRDbBGzsyFqxAkEAiPLOk1sgDgd0oMlMbXdX+fHQUwSBfgYBTMc0i/NklSPz3tm/wbfsnh61kZXd6yWVbJ+kn/rM5/I/JnKvtJnq4QJAJXwyPLRenxjPxa5xIh02H1Ywpczv9PrySNtXO+ezI4NHAaXXzvjA0TvCm0S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utpIHKQchpolbSuC0vgaHpSjO9OUs1fpnK/JjZq9o8DatUsA0n4Fccec9NBbV5dy5yrwro7xmDpsevp1/IeiIssi1+iD+nBWqqVFx7GVQIDAQABAoGAODaXjO3rSePE+h+GNy7FhCZB+lA0JYGyG5bGkJLLTJi7U4Dnm68zdvFDX3fJ43LvRVTqxxnJTimyuy/tXDi4nblrGSnP3P4AMvcAEeBIaC75Xqx/RBD4j1hcXRA2zMT6pZKaizqPj8R64U5+L1OAmj3SbS9royp+55rFHVA1qPECQQDUtU5TOp4T7dl5czeZBn7CeJAWDY7i1zQNmHTbgtrbWLxFxyfU+9BTfxp0QQSGbuO7hx9yHuZ33qfqjJOmvET/AkEAzHnCMiNM9ZFbfrTn1isNmRS7Iu+O9PKk2nkeFtQAbZJ4I9fm8aFll69yqoY6iZFsZ4YqEn16ruwknDc43TNQqwJAEHfhEoyNRJm7pq2G9nAMTF4tOaffEiz7OLo/AefFrgnWuchLiy/b1zsV/z4xbX8UXqZ9hsZhrZItiflMTTJyXQJABaDkY5TtLWVO63H3X8HXofscG54UhVGYkBr9ZQt454s8m1/6D3St4zsFIQSI3/iMz1y2E8Q4eFAvwc0TV6Nt+QJBAIYGAZOh+0VNoiLr8M9XOgrRNYCfA7xKdRdCjjFjBQdCgqQ11E6IsdHZTM/ethaM2BDYuF+M2EKOpxcJV3ktz38=";
+        string lklPubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKPK6iG+eNwCRRs1lzE4bUyp6n0GMcj9s6lEPLIEYRpBHCCHpfGZ422SLwHqQ9zcU88lMbqfuSfQuJiPhNAqMHgmT7n2gYfxotL311lw1qG2ARJRSIyQ3oHXS6GBe9kFRWK8I/sVbuRxeV+toUs9N2EPjKequY28oxl9+AU3U6gQIDAQAB";
         
         public string LkLGetToken()
         {
@@ -1285,77 +1287,160 @@ namespace MySystem
             req.Add("target", target);
             string reqStr = Newtonsoft.Json.JsonConvert.SerializeObject(req);
             function.WriteLog("请求参数\n" + reqStr, "拉卡拉设置服务费");
-            reqStr = LklEncrypt(reqStr);
+            reqStr = "{\"data\":\"" + LklEncrypt(reqStr) + "\"}";
             function.WriteLog("加密参数\n" + reqStr, "拉卡拉设置服务费");
-            string result = function.PostWebRequest(lklReqUrl + "/htkterminal/open/terminal/change/activity/amount", reqStr, headers, "application/json");
+            function.WriteLog("请求地址\n" + lklReqUrl + "/htkterminal/open/terminal/change/activity/amount", "拉卡拉设置服务费");
+            string result = PostWebRequest(lklReqUrl + "/htkterminal/open/terminal/change/activity/amount", reqStr, headers);
             function.WriteLog("返回报文\n" + result + "\n\n\n", "拉卡拉设置服务费");
             return result;
         }
-        public string LkLSetFee(string sn, decimal rate = 0.6M, int fee = 0)
+        public string LkLSetFee(string merNo, decimal rate = 0.6M, int fee = 0)
         {
             List<Dictionary<string, string>> innerParamList = new List<Dictionary<string, string>>();
             Dictionary<string, string> item = new Dictionary<string, string>();
-            item.Add("feeType", "R1012");
+            item.Add("feeType", "CREDIT_CARD");
             item.Add("fee", rate.ToString("f2"));
             innerParamList.Add(item);
             Dictionary<string, string> headers = new Dictionary<string, string>();
-            headers.Add("Authorization", "bearer " + LkLGetToken());
-            headers.Add("X-Trace", function.get_Random(32));
-            function.WriteLog("请求地址\n" + lkbReqUrl2, "来客吧L吧设置费率");
+            headers.Add("Authorization", "bearer a54b216a-18b7-4a0b-b6b7-b37eee813b6e");// + LkLGetToken());
+            function.WriteLog("请求地址\n" + lkbReqUrl2, "拉卡拉设置费率");
             Dictionary<string, object> obj = new Dictionary<string, object>();
-            obj.Add("factorySequenceNo", sn);
-            obj.Add("productCode", "100");
-            obj.Add("productName", "来客吧");
+            obj.Add("productCode", "");
             obj.Add("fees", innerParamList);
             string content = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
-            function.WriteLog("明文参数\n" + content, "来客吧L吧设置费率");
-            content = LkbEncrypt2(content);
-            string signstr = LkbSign(content);
-            headers.Add("X-Sign", signstr);
-            string req = "{\"param\":\"" + content + "\"}";
-            function.WriteLog("加密参数\n" + req, "来客吧L吧设置费率");
-            string result = function.PostWebRequest(lkbReqUrl2, req, headers, "application/json");
-            function.WriteLog("返回报文\n" + result + "\n\n\n", "来客吧L吧设置费率");
+            function.WriteLog("明文参数\n" + content, "拉卡拉设置费率");
+            content = LklEncrypt(content);
+            string req = "{\"dto\":\"" + content + "\"}";
+            function.WriteLog("加密参数\n" + req, "拉卡拉设置费率");
+            string result = function.PostWebRequest(lklReqUrl + "/htkmerchants/channel/customer/update/fee/" + merNo, req, headers);
+            function.WriteLog("返回报文\n" + result + "\n\n\n", "拉卡拉设置费率");
             return result;
         }
 
         public string LklEncrypt(string data)
         {
-            var rsa = RSA.Create();
-            var key = Convert.FromBase64String(lklPriKey);
-            var content = Encoding.UTF8.GetBytes(data);
-            rsa.ImportPkcs8PrivateKey(key, out _);
+            // var rsa = RSA.Create();
+            // var key = Convert.FromBase64String(lklPriKey);
+            // var content = Encoding.UTF8.GetBytes(data);
+            // rsa.ImportPkcs8PrivateKey(key, out _);
+            // // rsa.ImportParameters(ImportPublicKey(lklPriKey));
 
-            var result = LklEncryptData(rsa, content);
+            // // var result = LklEncryptData(rsa, content);
+            // var result = rsa.Encrypt(content, RSAEncryptionPadding.Pkcs1);
 
-            return Convert.ToBase64String(result);
-            // return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, lklPriKey).Encrypt(data);
+            // return Convert.ToBase64String(result);
+            // return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, lklPriKey).Encrypt2(data);
+
+            // byte[] publicKey = Encoding.UTF8.GetBytes(lklPriKey);
+            // using (var x509 = new X509Certificate2(publicKey))
+            // {
+            //     using (var rsa = x509.GetRSAPrivateKey())
+            //     {
+            //         var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(data), RSAEncryptionPadding.Pkcs1);
+            //         return Convert.ToBase64String(buff);
+            //     }
+            // } 
+
+            return new RSAForJava().EncryptByPrivateKey(data, lklPriKey);
+        }
+
+        public string LklDecrypt(string data)
+        {
+            // var rsa = RSA.Create();
+            // var key = Convert.FromBase64String(lklPubKey);
+            // var content = Convert.FromBase64String(data);
+            // rsa.ImportSubjectPublicKeyInfo(key, out _);
+
+            // string result = "";
+            // List<byte> cache = new List<byte>();
+            // for (int i = 0; i < content.Length; i++)
+            // {
+            //     cache.Add(content[i]);
+            //     if ((i + 1) % 128 == 0 || i + 1 == content.Length)
+            //     {
+            //         var ContentArray = rsa.Decrypt(cache.ToArray(), RSAEncryptionPadding.OaepSHA1);
+            //         result += System.Text.Encoding.UTF8.GetString(ContentArray);
+            //         cache.Clear();
+            //     }
+            // }
+            // return result;
+
+
+            // 解码Base64编码的公钥和数据
+            // byte[] keyBytes = Convert.FromBase64String(lklPubKey);
+            // byte[] dataBytes = Convert.FromBase64String(data);
+
+            // // 创建RSA对象并初始化为解密模式
+            // using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
+            // {
+            //     rsa.ImportSubjectPublicKeyInfo(keyBytes, out _);
+
+            //     int blockSize = rsa.KeySize / 8;
+            //     using (MemoryStream ms = new MemoryStream())
+            //     {
+            //         for (int i = 0, offset = 0, length = dataBytes.Length; length - offset > 0; i++, offset = i * blockSize)
+            //         {
+            //             int chunkSize = Math.Min(blockSize, length - offset);
+            //             byte[] decryptedChunk = rsa.Decrypt(dataBytes.AsSpan(offset, chunkSize).ToArray(), false);
+            //             ms.Write(decryptedChunk, 0, decryptedChunk.Length);
+            //         }
+
+            //         return Encoding.UTF8.GetString(ms.ToArray());
+            //     }
+
+            // }
+
+            // return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, "", lklPubKey).Decrypt2(data);
+            return new RSAForJava().DecryptByPublicKey(data, lklPubKey);
         }
 
         public byte[] LklEncryptData(RSA rsa, byte[] data)
         {
-            using var memoryStream = new System.IO.MemoryStream();
-            int offset = 0;
-            byte[] buffer;
-    
-            while (offset < data.Length)
+            // using var memoryStream = new System.IO.MemoryStream();
+            // int offset = 0;
+            // byte[] buffer;
+
+            // while (offset < data.Length)
+            // {
+            //     if (offset + 64 < data.Length)
+            //     {
+            //         buffer = data.AsSpan(offset, 64).ToArray();
+            //     }
+            //     else
+            //     {
+            //         buffer = data.AsSpan(offset, data.Length - offset).ToArray();
+            //     }
+
+            //     byte[] encrypted = rsa.Encrypt(buffer, RSAEncryptionPadding.Pkcs1);
+            //     memoryStream.Write(encrypted);
+
+            //     offset += buffer.Length;
+            // }
+
+            // return memoryStream.ToArray();
+            int inputLen = data.Length;
+            var memoryStream = new System.IO.MemoryStream();
+            int offSet = 0;
+            byte[] cache;
+            int i = 0;
+            // 对数据分段加密
+            while (inputLen - offSet > 0)
             {
-                if (offset + 117 < data.Length)
+                if (inputLen - offSet > 117)
                 {
-                    buffer = data.AsSpan(offset, 117).ToArray();
+                    cache = data.AsSpan(offSet, 117).ToArray();
                 }
                 else
                 {
-                    buffer = data.AsSpan(offset, data.Length - offset).ToArray();
+                    cache = data.AsSpan(offSet, inputLen - offSet).ToArray();
                 }
-    
-                byte[] encrypted = rsa.Encrypt(buffer, RSAEncryptionPadding.Pkcs1);
+                byte[] encrypted = rsa.Encrypt(cache, RSAEncryptionPadding.OaepSHA1);
                 memoryStream.Write(encrypted);
-    
-                offset += buffer.Length;
+                i++;
+                offSet = i * 117;
             }
-    
-            return memoryStream.ToArray();
+            byte[] encryptedData = memoryStream.ToArray();
+            return encryptedData;
         }
         
         #endregion

+ 9 - 1
AppStart/Helper/RSAForJava.cs

@@ -91,6 +91,14 @@ namespace MySystem
             AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
             return pubKey;
         }
+        private AsymmetricKeyParameter GetPublicKeyParameter2(string s)
+        {
+            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
+            byte[] publicInfoByte = System.Text.Encoding.UTF8.GetBytes(s);
+            Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入   
+            AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
+            return pubKey;
+        }
         private AsymmetricKeyParameter GetPrivateKeyParameter(string s)
         {
             s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
@@ -149,7 +157,7 @@ namespace MySystem
                 for (int i = 0; i < byteData.Length; i++)
                 {
                     cache.Add(byteData[i]);
-                    if ((i + 1) % 256 == 0 || i + 1 == byteData.Length)
+                    if ((i + 1) % 128 == 0 || i + 1 == byteData.Length)
                     {
                         var ResultData = engine.ProcessBlock(cache.ToArray(), 0, cache.ToArray().Length);
                         result += System.Text.Encoding.UTF8.GetString(ResultData);

+ 41 - 0
AppStart/Helper/RSAHelper.cs

@@ -90,6 +90,15 @@ namespace MySystem
 			return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
 		}
 
+		public string Decrypt2(string cipherText)
+		{
+			if (_publicKeyRsaProvider == null)
+			{
+				throw new Exception("_publicKeyRsaProvider is null");
+			}
+			return Encoding.UTF8.GetString(_publicKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
+		}
+
 		#endregion
 
 		#region 加密
@@ -126,6 +135,38 @@ namespace MySystem
             return Convert.ToBase64String(outBytes);
 		}
 
+		public string Encrypt2(string text)
+		{
+			if (_privateKeyRsaProvider == null)
+			{
+				throw new Exception("_privateKeyRsaProvider is null");
+			}
+            #region 分段加密
+            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(text);
+            int bufferSize = (_privateKeyRsaProvider.KeySize / 8) - 11;
+			byte[] buffer = new byte [bufferSize] ;
+			byte[] outBytes = null;
+			using (MemoryStream input = new MemoryStream(dataToEncrypt))
+            using (MemoryStream ouput = new MemoryStream())
+            {
+                while (true)
+                {
+                    int readLine = input.Read(buffer, 0, bufferSize);
+                    if (readLine <= 0)
+                    {
+                        break;
+                    }
+                    byte[] temp = new byte[readLine];
+                    Array.Copy(buffer, 0, temp, 0, readLine);
+                    byte[] encrypt = _privateKeyRsaProvider.Encrypt(temp, RSAEncryptionPadding.Pkcs1);
+                    ouput.Write(encrypt, 0, encrypt.Length);
+                }
+                outBytes = ouput.ToArray();
+            }
+            #endregion
+            return Convert.ToBase64String(outBytes);
+		}
+
 		#endregion
 
 		#region 使用私钥创建RSA实例

+ 5 - 1
Controllers/HomeController.cs

@@ -73,7 +73,11 @@ namespace MySystem.Controllers
             // return PublicImportDataService.Instance.LkbSetDeposit("00000302QRNL15510103", 299);
             // return PublicImportDataService.Instance.LkbSetFee("00000302QRNL20019214", 0.63M, 300);
             
-            return PublicImportDataService.Instance.LkLSetDeposit("0000010222ATBEL00292", 299);
+            // return PublicImportDataService.Instance.LkLSetDeposit("0000010222ATBEL00292", 299);
+
+            string content = "YXzIAh6eQG30ei6iTQiqGpxRNk1gliq/ZpgWmr+HcF9BSKFSunqsJPaeDw7EL1lMvocDewnMaZivCSwlQA4TRxD/KkCBv3WmRRvdGXNz+4n0Dh5XGebhe3Uds2mEdChCDjUPhXIS5sCIT0eYN+8Z4y594qrsetUD/fv5e45lYDRhnEiKUxKTiJ32zYKzri6RU7ssV18KY2tEZnfmhpItO61kGE0UW2eV0WsKmb+YH/8w99i1cTGIvn5MnZu3i01d2uinpcRGPuVLVcKkfNU8fnYYkgDzm0chLu4SSyzVNrHTZuXsJoJ6qxcZCwuqfn6NxMNVh/TKtup7Jk1EwgltVwKxqNGEXmOSuAXytbsh4HIFe4Bd7qHu56iFcJHkoqsh/5m62J4iTZQf/KU6SHpJOX7XXz06DBxCa7YZPrSProoxphV9Xd0KcFw5QvyxdYOLLExU8qaHQAAR/BAF/IXhjLIESjabBvzmq9r77GUyirYkcfBq3ohBpHCaE6F7N8gPAHeSNd8Ox7piYy+Hyqos22Nc+rj4yAlGIgFG21W8QVfFuL0q3NYuCpCkJd58DaIQFfsypY9i1XZEOj7wNyafqtVx95F9Y3Vm4XTfglj27K7EUI6jdbu1xErAo7JjyTM8N/66weR6sX9z2aJYTcJneoPAfxTMz+XoSNGDOj2J76Y=";
+            
+            return PublicImportDataService.Instance.LklDecrypt(content);
         }
     
     }

+ 1 - 0
MySystem.csproj

@@ -50,6 +50,7 @@
     </Reference>
   </ItemGroup>
   <ItemGroup>
+    <PackageReference Include="BouncyCastle" Version="1.8.9" />
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
     <PackageReference Include="RabbitMQ.Client" Version="6.2.2" />
     <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />