-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilities.cs
More file actions
406 lines (338 loc) · 15.2 KB
/
Utilities.cs
File metadata and controls
406 lines (338 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
namespace ProjectDotNet20
{
internal class Utilities
{
public static void webRequest2(string pzUrl, string pzBody, string pzAuthorization, string pzHeaders,
string pzContentType, string pzMethod, bool zgetByte, out string pzResponse)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
delegate
{
return true;
});
ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
}
catch { }
pzResponse = string.Empty;
HttpWebResponse _rp = null;
WebRequest _rq = null;
try
{
//ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); // framework 4.0 only
///*SecurityProtocolType.Tls |
//SecurityProtocolType.Tls12 |
//SecurityProtocolType.Tls11; */
//ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
_rq = WebRequest.Create(pzUrl);
_rq.Method = pzMethod;
_rq.Timeout = 300000;
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
if (!string.IsNullOrEmpty(pzContentType))
{
if(pzContentType.Contains("multipart/form-data"))
{
_rq.ContentType = "multipart/form-data; boundary=" + boundary;
}
else
{
_rq.ContentType = pzContentType;
}
}
if (!string.IsNullOrEmpty(pzAuthorization))
_rq.Headers.Add(pzAuthorization);
if (!string.IsNullOrEmpty(pzHeaders))
{
var _doc = new XmlDocument();
_doc.LoadXml(pzHeaders);
var _headerNodes = _doc.DocumentElement.GetElementsByTagName("Header");
foreach (XmlNode _headerNode in _headerNodes)
{
var _nodeKey = _headerNode.SelectNodes("Key");
var _nodeValue = _headerNode.SelectNodes("Value");
if (_nodeKey == null || string.IsNullOrEmpty(_nodeKey[0].InnerText) ||
_nodeValue == null || string.IsNullOrEmpty(_nodeValue[0].InnerText)) continue;
_rq.Headers.Add(string.Format("{0}:{1}",
_nodeKey[0].InnerText, _nodeValue[0].InnerText));
}
}
if (!string.IsNullOrEmpty(pzBody))
{
if (pzContentType.Contains("multipart/form-data"))
{
byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
/// the last boundary.
byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
/// the form data, properly formatted
string formdataTemplate = " ; name=\"{0}\"\r\n\r\n{1}";
/// Added to track if we need a CRLF or not.
bool bNeedsCRLF = false;
Dictionary<string, object> postParameters = new Dictionary<string, object>();
//pzBody truyền vào dạng: key1=value1&key2=value2
foreach (string _data in pzBody.Split('&'))
{
string _key = _data.Split('=')[0];
string _value = _data.Split('=')[1];
postParameters.Add(_key, _value);
}
byte[] formData = GetMultipartFormData(postParameters, boundary);
string z123result = System.Text.Encoding.UTF8.GetString(formData);
_rq.ContentLength = formData.Length;
using (var rs = _rq.GetRequestStream())
{
rs.Write(formData, 0, formData.Length);
rs.Close();
}
}
else
{
var _buffer = Encoding.UTF8.GetBytes(pzBody);
_rq.ContentLength = _buffer.Length;
using (var rs = _rq.GetRequestStream())
{
rs.Write(_buffer, 0, _buffer.Length);
rs.Close();
}
}
}
else
_rq.ContentLength = 0;
_rp = (HttpWebResponse)_rq.GetResponse();
using (var _rs = _rp.GetResponseStream())
{
if (!zgetByte)
{
using (var _sr = new StreamReader(_rs))
{
pzResponse = _sr.ReadToEnd();
}
}
else
{
using (BinaryReader br = new BinaryReader(_rp.GetResponseStream()))
{
var _t = br.ReadBytes(2000000);
//pzResponse = br.ReadBytes(2000000);
pzResponse = Convert.ToBase64String(_t, 0, _t.Length);
}
}
}
}
catch (Exception _ex)
{
var _we = _ex as WebException;
if (_we != null)
{
_rp = (HttpWebResponse)_we.Response;
if (_rp != null)
{
using (var _rs = _rp.GetResponseStream())
using (var _sr = new StreamReader(_rs))
{
var _zExMsg = _sr.ReadToEnd();
if (!string.IsNullOrEmpty(_zExMsg))
{
pzResponse = string.Format("ERR_WEBSERVICE:{0}", _zExMsg);
return;
}
}
}
}
pzResponse = string.Format("ERR_WEBSERVICE:{0}", _ex.Message);
}
finally
{
if (_rp != null)
{
_rp.Close();
// _rp.Dispose();
_rp = null;
}
if (_rq != null) _rq = null;
}
}
internal static X509Certificate2 getCertificateBySerial(string pzSerial)
{
var _x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
_x509Store.Open(OpenFlags.ReadOnly);
var _enumerator = _x509Store.Certificates.GetEnumerator();
while (_enumerator.MoveNext())
{
var _current = _enumerator.Current;
if (_current.GetSerialNumberString().ToUpper().CompareTo(pzSerial.ToUpper().Trim()) == 0)
{
try
{
if (!_current.HasPrivateKey)
throw new Exception("Không lấy được private key, chọn chứng thư khác!");
}
catch
{
throw new Exception("Không lấy được private key, chọn chứng thư khác!");
}
return _current;
}
}
return null;
}
internal static string getBase64CertBySerial (string pzSerialCert)
{
X509Certificate2 _certificateBySerial = getCertificateBySerial(pzSerialCert);
byte[] _rawData = _certificateBySerial.RawData;
var _zCertString = Convert.ToBase64String(_rawData);
return _zCertString;
}
public static string signHashCert(string pzHashValue, string pzSerial)
{
var _zResult = string.Empty;
try
{
RSACryptoServiceProvider _rSACryptoServiceProvider = null;
var _x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
_x509Store.Open(OpenFlags.ReadOnly);
var _enumerator = _x509Store.Certificates.GetEnumerator();
while (_enumerator.MoveNext())
{
var _current = _enumerator.Current;
if (_current.GetSerialNumberString().ToUpper() == pzSerial.ToUpper())
{
_rSACryptoServiceProvider = (RSACryptoServiceProvider)_current.PrivateKey;
if (_rSACryptoServiceProvider == null)
return "ERR:-2";
break;
}
}
var _zText = Convert.ToBase64String(_rSACryptoServiceProvider.SignHash(Convert.FromBase64String(pzHashValue), CryptoConfig.MapNameToOID("SHA1")));
_x509Store.Close();
_zResult = _zText;
}
catch (Exception _ex)
{
//if (_ex.Message.Contains("cancelled by the user"))
// _zResult = "ERR:-1";
//else
// _zResult = "ERR:-3 " + _ex;
throw _ex;
}
return _zResult;
}
public static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
needsCLRF = true;
//if (param.Value is FileParameter)
//{
// FileParameter fileToUpload = (FileParameter)param.Value;
// // Add just the first part of this param, since we will write the file data directly to the Stream
// string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
// boundary,
// param.Key,
// fileToUpload.FileName ?? param.Key,
// fileToUpload.ContentType ?? "application/octet-stream");
// formDataStream.Write(encoding.GetBytes(header), , encoding.GetByteCount(header));
// // Write the file data directly to the Stream, rather than serializing it to a string.
// formDataStream.Write(fileToUpload.File, , fileToUpload.File.Length);
//}
//else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
public static string signHashString(string pzStringValue, string pzSerial, string cryptType)
{
var _zResult = string.Empty;
try
{
RSACryptoServiceProvider _rSACryptoServiceProvider = null;
var _x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
_x509Store.Open(OpenFlags.ReadOnly);
var _enumerator = _x509Store.Certificates.GetEnumerator();
while (_enumerator.MoveNext())
{
var _current = _enumerator.Current;
if (_current.GetSerialNumberString().ToUpper() == pzSerial.ToUpper())
{
_rSACryptoServiceProvider = (RSACryptoServiceProvider)_current.PrivateKey;
if (_rSACryptoServiceProvider == null)
return "ERR:-2";
break;
}
}
byte[] rgbHash = Encoding.ASCII.GetBytes(pzStringValue);
var _zText = Convert.ToBase64String(_rSACryptoServiceProvider.SignData(rgbHash, CryptoConfig.CreateFromName(cryptType)));
_x509Store.Close();
_zResult = _zText;
}
catch (Exception _ex)
{
//if (_ex.Message.Contains("cancelled by the user"))
// _zResult = "ERR:-1";
//else
// _zResult = "ERR:-3 " + _ex;
throw _ex;
}
return _zResult;
}
public static int MimeSampleSize = 256;
public static string DefaultMimeType = "application/octet-stream";
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static uint FindMimeFromData(
uint pBC,
[MarshalAs(UnmanagedType.LPStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
uint cbSize,
[MarshalAs(UnmanagedType.LPStr)] string pwzMimeProposed,
uint dwMimeFlags,
out uint ppwzMimeOut,
uint dwReserverd
);
public static string GetMimeFromBytes(byte[] data)
{
try
{
uint mimeType;
FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0);
var mimePointer = new IntPtr(mimeType);
var mime = Marshal.PtrToStringUni(mimePointer);
Marshal.FreeCoTaskMem(mimePointer);
return mime ?? DefaultMimeType;
}
catch
{
return DefaultMimeType;
}
}
}
}