forked from DigitalRuby/ExchangeSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoUtility.cs
More file actions
1506 lines (1375 loc) · 58.5 KB
/
CryptoUtility.cs
File metadata and controls
1506 lines (1375 loc) · 58.5 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT LICENSE
Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#nullable enable
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ExchangeSharp
{
/// <summary>
/// Useful extension methods for all sorts of things. Who says a kitchen sink class is bad?
/// </summary>
public static class CryptoUtility
{
internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
internal static readonly DateTime UnixEpochLocal = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
internal static readonly Encoding Utf8EncodingNoPrefix = new UTF8Encoding(false, true);
static bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
static string chinaZoneId = isWindows ? "China Standard Time" : "Asia/Shanghai";
static TimeZoneInfo chinaZone = TimeZoneInfo.FindSystemTimeZoneById(chinaZoneId);
static string koreanZoneId = isWindows ? "Korea Standard Time" : "Asia/Seoul";
static TimeZoneInfo koreaZone = TimeZoneInfo.FindSystemTimeZoneById(koreanZoneId);
private static Func<DateTime> utcNowFunc = UtcNowFuncImpl;
private static DateTime UtcNowFuncImpl()
{
// this is the only place in the code that DateTime.UtcNow is allowed. DateTime.UtcNow and DateTime.Now should not exist anywhere else in the code.
return DateTime.UtcNow;
}
/// <summary>
/// Set utc now func for override CryptoUtility.UtcNow. Set to null to go back to default CryptoUtility.UtcNow.
/// This is primarily useful for unit or integration testing.
/// </summary>
/// <param name="utcNowFunc">Utc now override func</param>
public static void SetDateTimeUtcNowFunc(Func<DateTime> utcNowFunc)
{
CryptoUtility.utcNowFunc = utcNowFunc ?? UtcNowFuncImpl;
}
/// <summary>
/// Empty object array
/// </summary>
public static readonly object[] EmptyObjectArray = new object[0];
/// <summary>
/// Empty string array
/// </summary>
public static readonly string[] EmptyStringArray = new string[0];
/// <summary>
/// Throw ArgumentNullException if obj is null
/// </summary>
/// <param name="obj">Object</param>
/// <param name="name">Parameter name</param>
/// <param name="message">Message</param>
public static void ThrowIfNull(this object obj, string? name, string? message = null)
{
if (obj == null)
{
throw new ArgumentNullException(name, message);
}
}
/// <summary>
/// Throw ArgumentNullException if obj is null or whitespace
/// </summary>
/// <param name="obj">Object</param>
/// <param name="name">Parameter name</param>
/// <param name="message">Message</param>
public static void ThrowIfNullOrWhitespace(this string obj, string name, string? message = null)
{
if (string.IsNullOrWhiteSpace(obj))
{
throw new ArgumentNullException(name, message);
}
}
/// <summary>
/// Convert an object to string using invariant culture
/// </summary>
/// <param name="obj">Object</param>
/// <param name="defaultValue">Default value if null</param>
/// <returns>String</returns>
public static string ToStringInvariant(this object obj, string defaultValue = "")
{
return Convert.ToString(obj, CultureInfo.InvariantCulture) ?? defaultValue;
}
/// <summary>
/// Convert an object to string uppercase using invariant culture
/// </summary>
/// <param name="obj">Object</param>
/// <returns>String</returns>
public static string ToStringUpperInvariant(this object obj)
{
return ToStringInvariant(obj).ToUpperInvariant();
}
/// <summary>
/// Convert an object to string lowercase using invariant culture
/// </summary>
/// <param name="obj">Object</param>
/// <returns>String</returns>
public static string ToStringLowerInvariant(this object obj)
{
return ToStringInvariant(obj).ToLowerInvariant();
}
/// <summary>
/// Convenience method to compare strings. The default uses OrginalIgnoreCase.
/// </summary>
/// <param name="s">String</param>
/// <param name="other">Other string</param>
/// <param name="option">Option</param>
/// <returns>True if equal, false if not</returns>
public static bool EqualsWithOption(this string s, string other, StringComparison option = StringComparison.OrdinalIgnoreCase)
{
if (s == null || other == null)
{
return false;
}
return s.Equals(other, option);
}
/// <summary>
/// Decompress gzip bytes
/// </summary>
/// <param name="bytes">Bytes that are gzipped</param>
/// <returns>Uncompressed bytes</returns>
public static byte[] DecompressGzip(byte[] bytes)
{
using (var compressStream = new MemoryStream(bytes))
{
using (var zipStream = new GZipStream(compressStream, CompressionMode.Decompress))
{
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}
/// <summary>
/// Decompress deflate bytes
/// </summary>
/// <param name="bytes">Bytes that are Deflate</param>
/// <returns>Uncompressed bytes</returns>
public static byte[] DecompressDeflate(byte[] bytes)
{
using (var compressStream = new MemoryStream(bytes))
{
using (var zipStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}
public enum SourceTimeZone
{
/// <summary> time zone is specifically specified in string </summary>
AsSpecified,
Local, China, Korea, UTC,
}
/// <summary>
/// Convert object to a UTC DateTime
/// </summary>
/// <param name="obj">Object to convert</param>
/// <param name="defaultValue">Default value if no conversion is possible</param>
/// <returns>DateTime in UTC or defaultValue if no conversion possible</returns>
public static DateTime ToDateTimeInvariant(this object obj, SourceTimeZone sourceTimeZone = SourceTimeZone.UTC, DateTime defaultValue = default)
{
if (obj == null)
{
return defaultValue;
}
JValue? jValue = obj as JValue;
if (jValue != null && jValue.Value == null)
{
Logger.Error("Failed parsing of datetime - setting to default value");
return defaultValue;
}
DateTime dt = (DateTime)Convert.ChangeType(jValue == null ? obj : jValue.Value, typeof(DateTime), CultureInfo.InvariantCulture);
switch (sourceTimeZone)
{
case SourceTimeZone.AsSpecified:
throw new NotImplementedException(); // TODO: implement this when needed
case SourceTimeZone.Local:
return DateTime.SpecifyKind(dt, DateTimeKind.Local).ToUniversalTime(); // convert to UTC
case SourceTimeZone.China:
return TimeZoneInfo.ConvertTime(dt, chinaZone, TimeZoneInfo.Utc); // convert to UTC
case SourceTimeZone.Korea:
return TimeZoneInfo.ConvertTime(dt, koreaZone, TimeZoneInfo.Utc); // convert to UTC
case SourceTimeZone.UTC:
return DateTime.SpecifyKind(dt, DateTimeKind.Utc);
default:
throw new NotImplementedException($"Unexpected {nameof(sourceTimeZone)}: {sourceTimeZone}");
}
}
/// <summary>
/// Convert an object to another type using invariant culture. Consider using the string or DateTime conversions if you are dealing with those types.
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="obj">Object</param>
/// <param name="defaultValue">Default value if no conversion is possible</param>
/// <returns>Converted value or defaultValue if not conversion was possible</returns>
public static T ConvertInvariant<T>(this object obj, T defaultValue = default)
{
if (obj == null)
{
return defaultValue;
}
JValue? jValue = obj as JValue;
if (jValue != null && jValue.Value == null)
{
return defaultValue;
}
T result;
try
{
result = (T)Convert.ChangeType(jValue == null ? obj : jValue.Value, typeof(T), CultureInfo.InvariantCulture);
if (typeof(T) == typeof(decimal))
{
return (T)(object)((decimal)(object)result).Normalize();
}
}
catch
{
if (typeof(T) == typeof(bool))
{
// try zero or one
return (T)(object)((jValue ?? obj).ToStringInvariant() == "1");
}
else
{
// fallback to float conversion, i.e. 1E-1 for a decimal conversion will fail
string stringValue = (jValue == null ? obj.ToStringInvariant() : jValue.Value.ToStringInvariant());
if (string.IsNullOrWhiteSpace(stringValue)) return defaultValue;
decimal decimalValue = decimal.Parse(stringValue, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture);
return (T)Convert.ChangeType(decimalValue, typeof(T), CultureInfo.InvariantCulture);
}
}
return result;
}
/// <summary>
/// Covnert a secure string to a non-secure string
/// </summary>
/// <param name="s">SecureString</param>
/// <returns>Non-secure string</returns>
public static string ToUnsecureString(this SecureString s)
{
if (s == null)
{
return null;
}
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(s);
return Marshal.PtrToStringUni(valuePtr);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
/// <summary>
/// Convert a secure string to non-secure binary data
/// </summary>
/// <param name="s">SecureString</param>
/// <returns>Binary data</returns>
public static byte[]? ToUnsecureBytesUTF8(this SecureString? s)
{
if (s == null)
{
return null;
}
return ToUnsecureString(s).ToBytesUTF8();
}
/// <summary>
/// Decode a secure string that is in base64 format to binary data
/// </summary>
/// <param name="s">SecureString in base64 format</param>
/// <returns>Binary data</returns>
public static byte[]? ToBytesBase64Decode(this SecureString? s)
{
if (s == null)
{
return null;
}
return Convert.FromBase64String(ToUnsecureString(s));
}
/// <summary>
/// Convert a string to a secure string
/// </summary>
/// <param name="unsecure">Plain text string</param>
/// <returns>SecureString</returns>
public static SecureString ToSecureString(this string unsecure)
{
if (unsecure == null)
{
return null;
}
SecureString secure = new SecureString();
foreach (char c in unsecure)
{
secure.AppendChar(c);
}
return secure;
}
/// <summary>
/// Get utf-8 bytes from a string
/// </summary>
/// <param name="s">String</param>
/// <returns>UTF8 bytes or null if s is null</returns>
public static byte[] ToBytesUTF8(this string s)
{
if (s == null)
{
return null;
}
return Utf8EncodingNoPrefix.GetBytes(s);
}
/// <summary>
/// Convert utf-8 bytes to a string
/// </summary>
/// <param name="bytes"></param>
/// <param name="index">Offset</param>
/// <param name="length">Length</param>
/// <returns>UTF-8 string or null if bytes is null</returns>
public static string ToStringFromUTF8(this byte[] bytes, int index = 0, int length = 0)
{
if (bytes == null)
{
return null;
}
length = (length <= 0 ? bytes.Length : length);
return Utf8EncodingNoPrefix.GetString(bytes, index, length);
}
/// <summary>
/// Convert gzipped utf-8 bytes to a string
/// </summary>
/// <param name="bytes"></param>
/// <returns>UTF-8 string or null if bytes is null</returns>
public static string ToStringFromUTF8Gzip(this byte[] bytes)
{
if (bytes == null)
{
return null;
}
return DecompressGzip(bytes).ToStringFromUTF8();
}
/// <summary>
/// Convert Deflate utf-8 bytes to a string
/// </summary>
/// <param name="bytes"></param>
/// <returns>UTF-8 string or null if bytes is null</returns>
public static string ToStringFromUTF8Deflate(this byte[] bytes)
{
if (bytes == null)
{
return null;
}
return DecompressDeflate(bytes).ToStringFromUTF8();
}
/// <summary>
/// JWT encode - converts to base64 string first then replaces + with - and / with _
/// </summary>
/// <param name="input">Input string</param>
/// <returns>Encoded string</returns>
public static string JWTEncode(this byte[] input)
{
return Convert.ToBase64String(input)
.Trim('=')
.Replace('+', '-')
.Replace('/', '_');
}
/// <summary>
/// JWT encode - converts to base64 string first then replaces + with - and / with _
/// </summary>
/// <param name="input">Input string</param>
/// <returns>Encoded string</returns>
public static string JWTEncode(this string input)
{
return Convert.ToBase64String(input.ToBytesUTF8())
.Trim('=')
.Replace('+', '-')
.Replace('/', '_');
}
/// <summary>
/// JWT decode from JWTEncode
/// </summary>
/// <param name="input">Input</param>
/// <returns>Decoded string</returns>
public static string JWTDecodedString(this string input)
{
string output = input.Replace('-', '+').Replace('_', '/');
switch (output.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: output += "=="; break; // Two pad chars
case 3: output += "="; break; // One pad char
default: throw new ArgumentException("Bad JWT string: " + input);
}
return Convert.FromBase64String(output).ToStringFromUTF8();
}
/// <summary>
/// JWT decode from JWTEncode
/// </summary>
/// <param name="input">Input</param>
/// <returns>Decoded bytes</returns>
public static byte[] JWTDecodedBytes(this string input)
{
string output = input.Replace('-', '+').Replace('_', '/');
switch (output.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: output += "=="; break; // Two pad chars
case 3: output += "="; break; // One pad char
default: throw new ArgumentException("Bad JWT string: " + input);
}
return Convert.FromBase64String(output);
}
/// <summary>
/// Url encode extension - use this for ALL url encoding / escaping
/// </summary>
/// <param name="s">String to url encode</param>
/// <returns>Url encoded string</returns>
public static string UrlEncode(this string s)
{
return WebUtility.UrlEncode((s ?? string.Empty));
}
/// <summary>
/// Form encode extension - use this for ALL form encoding / escaping
/// </summary>
/// <param name="s">String to form encode</param>
/// <returns>Form encoded string</returns>
public static string FormEncode(this string s)
{
return (s ?? string.Empty)
.Replace("%", "%25")
.Replace("+", "%2B")
.Replace(' ', '+')
.Replace("&", "%26")
.Replace("=", "%3D")
.Replace("\r", "%0D")
.Replace("\n", "%0A")
.Replace(":", "%3A")
.Replace("/", "%2F")
.Replace("@", "%40")
.Replace(";", "%3B");
}
/// <summary>
/// Clamp a decimal to a min and max value
/// </summary>
/// <param name="minValue">Min value</param>
/// <param name="maxValue">Max value</param>
/// <param name="stepSize">Smallest unit value should be evenly divisible by</param>
/// <param name="value">Value to clamp</param>
/// <returns>Clamped value</returns>
public static decimal ClampDecimal(decimal minValue, decimal maxValue, decimal? stepSize, decimal value)
{
if (minValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(minValue));
}
else if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue));
}
else if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
else if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException(nameof(minValue));
}
if (stepSize.HasValue)
{
if (stepSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(stepSize));
}
decimal mod = value % stepSize.Value;
value -= mod;
}
if (maxValue > 0)
{
value = Math.Min(maxValue, value);
}
value = Math.Max(minValue, value);
return value.Normalize();
}
/// <summary>Remove trailing zeroes on the decimal.</summary>
/// <param name="value">The value to normalize.</param>
/// <returns>1.230000 becomes 1.23</returns>
public static decimal Normalize(this decimal value)
{
return value / 1.000000000000000000000000000000000m;
}
/// <summary>
/// Get a UTC date time from a unix epoch in seconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in seconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeSeconds(this double unixTimeStampSeconds)
{
return UnixEpoch.AddSeconds(unixTimeStampSeconds);
}
/// <summary>
/// Get a UTC date time from a unix epoch in seconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in seconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeSeconds(this long unixTimeStampSeconds)
{
return UnixEpoch.AddSeconds(unixTimeStampSeconds);
}
/// <summary>
/// Get a utc date time from a local unix epoch in seconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in seconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampLocalToDateTimeSeconds(this double unixTimeStampSeconds)
{
return UnixEpochLocal.AddSeconds(unixTimeStampSeconds).ToUniversalTime();
}
/// <summary>
/// Get a UTC date time from a unix epoch in milliseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeMilliseconds(this double unixTimeStampMilliseconds)
{
return UnixEpoch.AddMilliseconds(unixTimeStampMilliseconds);
}
/// <summary>
/// Get a UTC date time from a unix epoch in milliseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeMilliseconds(this long unixTimeStampMilliseconds)
{
return UnixEpoch.AddMilliseconds(unixTimeStampMilliseconds);
}
/// <summary>
/// Get a utc date time from a local unix epoch in milliseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param>
/// <returns>Local DateTime</returns>
public static DateTime UnixTimeStampLocalToDateTimeMilliseconds(this double unixTimeStampMilliseconds)
{
return UnixEpochLocal.AddMilliseconds(unixTimeStampMilliseconds).ToUniversalTime();
}
/// <summary>
/// Get a utc date time from a local unix epoch in milliseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param>
/// <returns>Local DateTime</returns>
public static DateTime UnixTimeStampLocalToDateTimeMilliseconds(this long unixTimeStampMilliseconds)
{
return UnixEpochLocal.AddMilliseconds(unixTimeStampMilliseconds).ToUniversalTime();
}
/// <summary>
/// Get a UTC date time from a unix epoch in microseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in microseconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeMicroseconds(this long unixTimeStampMicroseconds)
{
return UnixEpoch.AddTicks(unixTimeStampMicroseconds * 10);
}
/// <summary>
/// Get a UTC date time from a unix epoch in nanoseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeNanoseconds(this double unixTimeStampNanoseconds)
{
return UnixEpoch.AddTicks((long)unixTimeStampNanoseconds / 100);
}
/// <summary>
/// Get a UTC date time from a unix epoch in nanoseconds
/// </summary>
/// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param>
/// <returns>UTC DateTime</returns>
public static DateTime UnixTimeStampToDateTimeNanoseconds(this long unixTimeStampNanoseconds)
{
return UnixEpoch.AddTicks(unixTimeStampNanoseconds / 100);
}
/// <summary>
/// Get a unix timestamp in seconds from a DateTime
/// </summary>
/// <param name="dt">DateTime</param>
/// <returns>Unix epoch in seconds</returns>
public static double UnixTimestampFromDateTimeSeconds(this DateTime dt)
{
if (dt.Kind != DateTimeKind.Utc)
{
dt = dt.ToUniversalTime();
}
return (dt - UnixEpoch).TotalSeconds;
}
/// <summary>
/// Get a unix timestamp in milliseconds from a DateTime
/// </summary>
/// <param name="dt">DateTime</param>
/// <returns>Unix timestamp in milliseconds</returns>
public static double UnixTimestampFromDateTimeMilliseconds(this DateTime dt)
{
if (dt.Kind != DateTimeKind.Utc)
{
dt = dt.ToUniversalTime();
}
return (dt - UnixEpoch).TotalMilliseconds;
}
/// <summary>
/// Convert a timestamp to DateTime. If value is null, CryptoUtility.UtcNow is returned.
/// </summary>
/// <param name="value">Timestamp object (JToken, string, double, etc.)</param>
/// <param name="type">Type of timestamp</param>
/// <returns>DateTime</returns>
public static DateTime ParseTimestamp(object value, TimestampType type)
{
if (value == null || type == TimestampType.None)
{
return CryptoUtility.UtcNow;
}
switch (type)
{
case TimestampType.Iso8601Local:
return value.ToDateTimeInvariant(SourceTimeZone.Local);
case TimestampType.Iso8601China:
return value.ToDateTimeInvariant(SourceTimeZone.China);
case TimestampType.Iso8601Korea:
return value.ToDateTimeInvariant(SourceTimeZone.Korea);
case TimestampType.Iso8601UTC:
return value.ToDateTimeInvariant(SourceTimeZone.UTC);
case TimestampType.UnixNanoseconds:
return UnixTimeStampToDateTimeNanoseconds(value.ConvertInvariant<long>());
case TimestampType.UnixMicroeconds:
return UnixTimeStampToDateTimeMicroseconds(value.ConvertInvariant<long>());
case TimestampType.UnixMillisecondsDouble:
return UnixTimeStampToDateTimeMilliseconds(value.ConvertInvariant<double>());
case TimestampType.UnixMilliseconds:
return UnixTimeStampToDateTimeMilliseconds(value.ConvertInvariant<long>());
case TimestampType.UnixSecondsDouble:
return UnixTimeStampToDateTimeSeconds(value.ConvertInvariant<double>());
case TimestampType.UnixSeconds:
return UnixTimeStampToDateTimeSeconds(value.ConvertInvariant<long>());
default:
throw new ArgumentException("Invalid timestamp type " + type);
}
}
/// <summary>
/// Get a string that can be used for basic authentication. Put this in the 'Authorization' http header, and ensure you are using https.
/// </summary>
/// <param name="userName">User name or public key</param>
/// <param name="password">Password or private key</param>
/// <returns>Full authorization header text</returns>
public static string BasicAuthenticationString(string userName, string password)
{
return "Basic " + Convert.ToBase64String((userName + ":" + password).ToBytesUTF8());
}
/// <summary>
/// Forces GetJsonForPayload to serialize the value of this key and nothing else.
/// This is a little hacky, but allows posting arrays instead of dictionary to API for bulk calls.
/// Normally a good API design would require a dictionary post with an array key and then
/// an array of values, allowing other key/values to be posted with the bulk call,
/// but some API (I'm looking at you Bitmex) just accept an array and nothing else.
/// </summary>
public const string PayloadKeyArray = "__hacky_array_key__";
/// <summary>
/// Convert a payload into json. If payload contains key PayloadKeyArray, that item is used only and serialized by itself
/// </summary>
/// <param name="payload">Payload</param>
/// <returns>Json string</returns>
public static string GetJsonForPayload(this Dictionary<string, object> payload)
{
if (payload != null && payload.Count != 0)
{
if (payload.TryGetValue(PayloadKeyArray, out object array))
{
return JsonConvert.SerializeObject(array, DecimalConverter.Instance);
}
return JsonConvert.SerializeObject(payload, DecimalConverter.Instance);
}
return string.Empty;
}
public static string GetJsonForPayload(this Dictionary<string, object> payload, bool includeNonce = true)
{
if (includeNonce == false)
{
payload.Remove("nonce");
}
return (GetJsonForPayload(payload));
}
/// <summary>
/// Write a form to a request
/// </summary>
/// <param name="request">Request</param>
/// <param name="form">Form to write</param>
public static async Task WriteToRequestAsync(this IHttpWebRequest request, string form)
{
if (string.IsNullOrEmpty(form) && request.Method != "GET")
{
request.AddHeader("content-length", "0");
}
else if (!string.IsNullOrEmpty(form))
{
byte[] bytes = form.ToBytesUTF8();
request.AddHeader("content-length", bytes.Length.ToStringInvariant());
await request.WriteAllAsync(bytes, 0, bytes.Length);
}
}
/// <summary>
/// Write a payload form to a request
/// </summary>
/// <param name="request">Request</param>
/// <param name="payload">Payload</param>
/// <returns>The form string that was written</returns>
public static async Task<string> WritePayloadFormToRequestAsync(this IHttpWebRequest request, Dictionary<string, object> payload)
{
string form = GetFormForPayload(payload);
await WriteToRequestAsync(request, form);
return form;
}
/// <summary>
/// Write a payload json to a request
/// </summary>
/// <param name="request">Request</param>
/// <param name="payload">Payload</param>
/// <returns>The json string that was written</returns>
public static async Task<string> WritePayloadJsonToRequestAsync(this IHttpWebRequest request, Dictionary<string, object> payload)
{
string json = GetJsonForPayload(payload);
await WriteToRequestAsync(request, json);
return json;
}
/// <summary>
/// Get a form for a request (form-encoded, like a query string)
/// </summary>
/// <param name="payload">Payload</param>
/// <param name="includeNonce">Whether to add the nonce</param>
/// <param name="orderByKey">Whether to order by the key</param>
/// <param name="formEncode">True to use form encoding, false to use url encoding</param>
/// <returns>Form string</returns>
public static string GetFormForPayload(this IReadOnlyDictionary<string, object> payload, bool includeNonce = true, bool orderByKey = true, bool formEncode = true)
{
if (payload != null && payload.Count != 0)
{
StringBuilder form = new StringBuilder();
IEnumerable<KeyValuePair<string, object>> e = (orderByKey ? payload.OrderBy(kv => kv.Key) : payload.AsEnumerable<KeyValuePair<string, object>>());
foreach (KeyValuePair<string, object> keyValue in e)
{
if (!string.IsNullOrWhiteSpace(keyValue.Key) && keyValue.Value != null && (includeNonce || keyValue.Key != "nonce"))
{
string key = (formEncode ? keyValue.Key.FormEncode() : keyValue.Key.UrlEncode());
string value = (formEncode ? keyValue.Value.ToStringInvariant().FormEncode() : keyValue.Value.ToStringInvariant().UrlEncode());
form.Append($"{key}={value}&");
}
}
if (form.Length != 0)
{
form.Length--; // trim ampersand
}
return form.ToString();
}
return string.Empty;
}
/// <summary>
/// Append a dictionary of key/values to a url builder query
/// </summary>
/// <param name="uri">Uri builder</param>
/// <param name="payload">Payload to append</param>
public static void AppendPayloadToQuery(this UriBuilder uri, Dictionary<string, object> payload)
{
if (uri.Query.Length > 1)
{
uri.Query += "&";
}
foreach (var kv in payload)
{
uri.Query += $"{kv.Key.UrlEncode()}={kv.Value.ToStringInvariant().UrlEncode()}&";
}
uri.Query = uri.Query.Trim('&');
}
/// <summary>
/// Get a value from dictionary with default fallback
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="dictionary">Dictionary</param>
/// <param name="key">Key</param>
/// <param name="defaultValue">Default value</param>
/// <returns>Found value or default</returns>
public static TValue TryGetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
if (!dictionary.TryGetValue(key, out TValue value))
{
value = defaultValue;
}
return value;
}
/// <summary>
/// Copy dictionary to another dictionary
/// </summary>
/// <typeparam name="TKey">Key type</typeparam>
/// <typeparam name="TValue">Value type</typeparam>
/// <param name="sourceDictionary"></param>
/// <param name="destinationDictionary"></param>
public static void CopyTo<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> sourceDictionary, IDictionary<TKey, TValue> destinationDictionary)
{
foreach (var kv in sourceDictionary)
{
destinationDictionary[kv.Key] = kv.Value;
}
}
/// <summary>
/// Sign a message with SHA256 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key</param>
/// <returns>Signature in hex</returns>
public static string SHA256Sign(string message, string key)
{
return new HMACSHA256(key.ToBytesUTF8()).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString());
}
public static string SHA256Sign(string message, string key, bool UseASCII)
{
var encoding = new ASCIIEncoding();
return Convert.ToBase64String(new HMACSHA256(encoding.GetBytes(key)).ComputeHash(encoding.GetBytes(message)));
}
/// <summary>
/// Sign a message with SHA256 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key bytes</param>
/// <returns>Signature in hex</returns>
public static string SHA256Sign(string message, byte[] key)
{
return new HMACSHA256(key).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString());
}
/// <summary>
/// Sign a message with SHA256 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key bytes</param>
/// <returns>Signature in base64</returns>
public static string SHA256SignBase64(string message, byte[] key)
{
return Convert.ToBase64String(new HMACSHA256(key).ComputeHash(message.ToBytesUTF8()));
}
/// <summary>
/// Sign a message with SHA384 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key</param>
/// <returns>Signature in hex</returns>
public static string SHA384Sign(string message, string key)
{
return new HMACSHA384(key.ToBytesUTF8()).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString());
}
/// <summary>
/// Sign a message with SHA384 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key bytes</param>
/// <returns>Signature</returns>
public static string SHA384Sign(string message, byte[] key)
{
return new HMACSHA384(key).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString());
}
/// <summary>
/// Sign a message with SHA384 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key bytes</param>
/// <returns>Signature in base64</returns>
public static string SHA384SignBase64(string message, byte[] key)
{
return Convert.ToBase64String(new HMACSHA384(key).ComputeHash(message.ToBytesUTF8()));
}
/// <summary>
/// Sign a message with SHA512 hash
/// </summary>
/// <param name="message">Message to sign</param>
/// <param name="key">Private key</param>
/// <returns>Signature in hex</returns>
public static string SHA512Sign(string message, string key)
{
byte[] hashmessage;
using (var hmac = new HMACSHA512(key.ToBytesUTF8()))
{
var messagebyte = message.ToBytesUTF8();
hashmessage = hmac.ComputeHash(messagebyte);
}
return BitConverter.ToString(hashmessage).Replace("-", "");
}
/// <summary>
/// Sign a message with SHA512 hash
/// </summary>