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
namespace Devolutions.Cryptography
{
using System;
using System.IO;
using System.Text;
/// <summary>
/// Useful functions from Devolutions Crypto.
/// </summary>
public static class Utils
{
/// <summary>
/// Converts a base 64 string to a byte array.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A byte array.</returns>
public static byte[] Base64StringToByteArray(string data)
{
if (string.IsNullOrEmpty(data))
{
return null;
}
return DecodeFromBase64(data);
}
/// <summary>
/// Encode a byte array to a UTF8 encoded string.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A UTF8 encoded string.</returns>
[Obsolete("This method has been deprecated. Use ByteArrayToUtf8String instead.")]
public static string ByteArrayToString(byte[] data)
{
return ByteArrayToUtf8String(data);
}
/// <summary>
/// Encode a byte array to a UTF8 encoded string.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A UTF8 encoded string.</returns>
public static string ByteArrayToUtf8String(byte[] data)
{
if (data == null || data.Length == 0)
{
return null;
}
try
{
return Encoding.UTF8.GetString(data);
}
catch (DecoderFallbackException)
{
return null;
}
}
/// <summary>
/// Concatenate arrays together.
/// </summary>
/// <param name="list">List of arrays to concatenate.</param>
/// <returns>Returns the arrays concatenated into a single array. </returns>
public static byte[] ConcatArrays(params byte[][] list)
{
int length = 0;
for (int i = 0; i < list.Length; i++)
{
length += list[i].Length;
}
byte[] result = new byte[length];
int offset = 0;
for (int x = 0; x < list.Length; x++)
{
list[x].CopyTo(result, offset);
offset += list[x].Length;
}
return result;
}
/// <summary>
/// Compare two strings with constant-time equality.
/// </summary>
/// <param name="x">The first value to compare.</param>
/// <param name="y">The second value to compare.</param>
/// <returns>Returns false if the values are not equal is invalid or true if the values are equal. If there is an error,
/// it will trigger a DevolutionsCryptoException.</returns>
public static bool ConstantTimeEquals(string x, string y)
{
if (x == null)
{
x = string.Empty;
}
if (y == null)
{
y = string.Empty;
}
byte[] xBytes = Encoding.UTF8.GetBytes(x);
byte[] yBytes = Encoding.UTF8.GetBytes(y);
return ConstantTimeEquals(xBytes, yBytes);
}
/// <summary>
/// Compare two guids with constant-time equality.
/// </summary>
/// <param name="x">The first value to compare.</param>
/// <param name="y">The second value to compare.</param>
/// <returns>Returns false if the values are not equal is invalid or true if the values are equal. If there is an error,
/// it will trigger a DevolutionsCryptoException.</returns>
public static bool ConstantTimeEquals(Guid x, Guid y)
{
byte[] xBytes = x.ToByteArray();
byte[] yBytes = y.ToByteArray();
return ConstantTimeEquals(xBytes, yBytes);
}
/// <summary>
/// Compare two byte arrays with constant-time equality.
/// </summary>
/// <param name="x">The first value to compare.</param>
/// <param name="y">The second value to compare.</param>
/// <returns>Returns false if the values are not equal is invalid or true if the values are equal. If there is an error,
/// it will trigger a DevolutionsCryptoException.</returns>
public static bool ConstantTimeEquals(byte[] x, byte[] y)
{
if (x == null || y == null)
{
return x == null && y == null;
}
long res = Native.ConstantTimeEquals(x, (UIntPtr)x.Length, y, (UIntPtr)y.Length);
if (res < 0)
{
throw GetDevolutionsCryptoException(res);
}
return res == 1;
}
/// <summary>
/// Converts a base 64 string to a byte array.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A byte array.</returns>
[Obsolete("This method has been deprecated. Use DecodeFromBase64 instead.")]
public static byte[] Decode(string data)
{
return DecodeFromBase64(data);
}
/// <summary>
/// Converts a base 64 string to a byte array.
/// </summary>
/// <param name="base64">The data to convert.</param>
/// <returns>A byte array.</returns>
public static byte[] DecodeFromBase64(string base64)
{
if (string.IsNullOrEmpty(base64))
{
return null;
}
int length = GetDecodedBase64StringLength(base64);
if (length == 0)
{
return null;
}
byte[] buffer = new byte[length];
long decode_res = Native.DecodeNative(base64, (UIntPtr)base64.Length, buffer, (UIntPtr)buffer.Length);
if (decode_res == -1)
{
return null;
}
return buffer;
}
/// <summary>
/// Converts a base 64 url string to a byte array.
/// </summary>
/// <param name="base64url">The data to convert.</param>
/// <returns>A byte array.</returns>
public static byte[] DecodeFromBase64Url(string base64url)
{
if (string.IsNullOrEmpty(base64url))
{
return null;
}
byte[] buffer = new byte[base64url.Length];
long decode_res = Native.DecodeUrlNative(base64url, (UIntPtr)base64url.Length, buffer, (UIntPtr)buffer.Length);
if (decode_res == -1)
{
return null;
}
Array.Resize(ref buffer, (int)decode_res);
return buffer;
}
/// <summary>
/// Converts a byte array to a base 64 encoded string.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A base 64 string.</returns>
[Obsolete("This method has been deprecated. Use EncodeToBase64 instead.")]
public static string Encode(byte[] data)
{
return EncodeToBase64String(data);
}
/// <summary>
/// Converts a byte array to a base 64 encoded string.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A base 64 string.</returns>
public static string EncodeToBase64String(byte[] data)
{
if (data == null || data.Length == 0)
{
return null;
}
int length = GetEncodedBase64StringLength(data);
if (length == 0)
{
return null;
}
byte[] buffer = new byte[length];
long encode_res = Native.EncodeNative(data, (UIntPtr)data.Length, buffer, (UIntPtr)buffer.Length);
return ByteArrayToUtf8String(buffer);
}
/// <summary>
/// Converts a byte array to a base 64 url encoded string.
/// </summary>
/// <param name="data">The data to convert.</param>
/// <returns>A base 64 url string.</returns>
public static string EncodeToBase64UrlString(byte[] data)
{
if (data == null || data.Length == 0)
{
return null;
}
int length = (data.Length * 4 / 3) + 4;
byte[] buffer = new byte[length];
long encode_res = Native.EncodeUrlNative(data, (UIntPtr)data.Length, buffer, (UIntPtr)buffer.Length);
Array.Resize(ref buffer, (int)encode_res);
return ByteArrayToUtf8String(buffer);
}
/// <summary>
/// Calculate the length of the original buffer if the base 64 string is converted back.
/// Warning this method doesn't validate if the string is valid base64.
/// </summary>
/// <param name="base64">The base 64 string to calculate the resulting length.</param>
/// <returns>The original buffer length.</returns>
public static int GetDecodedBase64StringLength(string base64)
{
if (string.IsNullOrEmpty(base64) || base64.Length % 4 != 0)
{
return 0;
}
int padCount = 0;
for (int i = base64.Length - 1; i >= base64.Length - 2; i--)
{
if (base64[i] == '=')
{
padCount++;
}
}
return (3 * (base64.Length / 4)) - padCount;
}
/// <summary>
/// Calculate the length of the original buffer if the base 64 string is converted back.
/// Warning this method doesn't validate if the string is valid base64.
/// </summary>
/// <param name="base64">The base 64 string to calculate the resulting length.</param>
/// <returns>The original buffer length.</returns>
[Obsolete("This method has been deprecated. Use GetDecodedBase64StringLength instead.")]
public static int GetDecodedLength(string base64)
{
return GetDecodedBase64StringLength(base64);
}
/// <summary>
/// Calculate the length of the resulting array if the buffer is encoded in base64.
/// </summary>
/// <param name="buffer">The buffer to calculate the resulting length.</param>
/// <returns>The resulting base 64 buffer lentgh.</returns>
public static int GetEncodedBase64StringLength(byte[] buffer)
{
if (buffer == null)
{
return 0;
}
return ((4 * buffer.Length / 3) + 3) & ~3;
}
/// <summary>
/// Calculate the length of the resulting array if the buffer is encoded in base64.
/// </summary>
/// <param name="buffer">The buffer to calculate the resulting length.</param>
/// <returns>The resulting base 64 buffer lentgh.</returns>
[Obsolete("This method has been deprecated. Use GetEncodedBase64StringLength instead.")]
public static int GetEncodedLength(byte[] buffer)
{
return GetEncodedBase64StringLength(buffer);
}
/// <summary>
/// This method is exposed for a very specific use case. Do not rely on it.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="salt">The salt for the password hashing.</param>
/// <param name="logN">Iterations count.</param>
/// <param name="r">Block size.</param>
/// <param name="p">Parallelism factor.</param>
/// <returns>The resulting hash.</returns>
public static string ScryptSimple(byte[] password, byte[] salt, byte logN, uint r, uint p)
{
if (password == null || salt == null)
{
throw new DevolutionsCryptoException(ManagedError.InvalidParameter);
}
long length = (int)Native.ScryptSimpleSize();
byte[] hash = new byte[length];
long res = Native.ScryptSimple(password, (UIntPtr)password.Length, salt, (UIntPtr)salt.Length, logN, r, p, hash, (UIntPtr)hash.Length);
if (res < 0)
{
HandleError(res);
}
Array.Resize(ref hash, (int)res);
return ByteArrayToUtf8String(hash);
}
/// <summary>
/// Converts a string to a UTF8 encoded byte array.
/// </summary>
/// <param name="data">The string to convert.</param>
/// <returns>A UTF8 string in a byte array.</returns>
[Obsolete("This method has been deprecated. Use StringToUtf8ByteArray instead.")]
public static byte[] StringToByteArray(string data)
{
return StringToUtf8ByteArray(data);
}
/// <summary>
/// Converts a string to a UTF8 encoded byte array.
/// </summary>
/// <param name="data">The string to convert.</param>
/// <returns>A UTF8 string in a byte array.</returns>
public static byte[] StringToUtf8ByteArray(string data)
{
if (data == null)
{
return null;
}
return Encoding.UTF8.GetBytes(data);
}
/// <summary>
/// Converts a byte array to a base 64 encoded string.
/// </summary>
/// <param name="bytes">The data to convert.</param>
/// <returns>A base 64 string.</returns>
[Obsolete("This method has been deprecated. Use EncodeToBase64 instead.")]
public static string ToBase64String(byte[] bytes)
{
if (bytes == null || bytes.Length == 0)
{
return null;
}
return Encode(bytes);
}
/// <summary>
/// Validate that the buffer is from the Devolutions Crypto Library.
/// </summary>
/// <param name="data">The buffer to validate.</param>
/// <param name="type">The data type to validate.</param>
/// <returns>Returns true if the buffer received matches the data type.</returns>
public static bool ValidateHeader(byte[] data, DataType type)
{
if (data == null)
{
return false;
}
long result = Native.ValidateHeader(data, (UIntPtr)data.Length, (ushort)type);
if (result < 0)
{
HandleError(result);
}
return Convert.ToBoolean(result);
}
/// <summary>
/// Validate that the base 64 string is from the Devolutions Crypto Library.
/// Performance : Use ValidateHeader(byte[], DataType) for more performance if possible.
/// </summary>
/// <param name="base64">The buffer to validate.</param>
/// <param name="type">The data type to validate.</param>
/// <returns>Returns true if the base 64 string received matches the data type.</returns>
public static bool ValidateHeaderFromBase64(string base64, DataType type)
{
byte[] data = DecodeFromBase64(base64);
return ValidateHeader(data, type);
}
/// <summary>
/// Validate that the stream data is from the Devolutions Crypto Library.
/// The stream must support both Seeking and Reading.
/// Performance : Use ValidateHeader(byte[], DataType) for more performance if possible.
/// </summary>
/// <param name="stream">The stream to validate.</param>
/// <param name="type">The data type to validate.</param>
/// <returns>Returns true if the stream data received matches the data type.</returns>
public static bool ValidateHeaderFromStream(Stream stream, DataType type)
{
if (stream == null)
{
return false;
}
try
{
if (!stream.CanSeek)
{
throw new DevolutionsCryptoException(ManagedError.CanNotSeekStream);
}
if (!stream.CanRead)
{
throw new DevolutionsCryptoException(ManagedError.CanNotReadStream);
}
long originalPosition = stream.Position;
byte[] buffer = new byte[8];
int count = stream.Read(buffer, 0, 8);
stream.Position = originalPosition;
if (count < 8)
{
return false;
}
return ValidateHeader(buffer, type);
}
catch (DevolutionsCryptoException)
{
throw;
}
catch (Exception ex)
{
DevolutionsCryptoException exception = new DevolutionsCryptoException(ManagedError.Error, exception: ex);
throw exception;
}
}
/// <summary>
/// Validate that the buffer is from the Devolutions Crypto Library.
/// </summary>
/// <param name="data">The buffer to validate.</param>
/// <param name="type">The data type to validate.</param>
/// <returns>Returns true if the buffer received matches the data type.</returns>
[Obsolete("This method has been deprecated. Use ValidateHeader instead.")]
public static bool ValidateSignature(byte[] data, DataType type)
{
return ValidateHeader(data, type);
}
/// <summary>
/// Validate that the base 64 string is from the Devolutions Crypto Library.
/// Performance : Use ValidateHeader(byte[], DataType) for more performance if possible.
/// </summary>
/// <param name="base64">The buffer to validate.</param>
/// <param name="type">The data type to validate.</param>
/// <returns>Returns true if the base 64 string received matches the data type.</returns>
[Obsolete("This method has been deprecated. Use ValidateHeaderFromBase64 instead.")]
public static bool ValidateSignatureFromBase64(string base64, DataType type)
{
return ValidateHeaderFromBase64(base64, type);
}
/// <summary>
/// Validate that the stream data is from the Devolutions Crypto Library.
/// The stream must support both Seeking and Reading.
/// Performance : Use ValidateHeader(byte[], DataType) for more performance if possible.
/// </summary>
/// <param name="stream">The stream to validate.</param>
/// <param name="type">The data type to validate.</param>
/// <returns>Returns true if the stream data received matches the data type.</returns>
[Obsolete("This method has been deprecated. Use ValidateHeaderFromStream instead.")]
public static bool ValidateSignatureFromStream(Stream stream, DataType type)
{
return ValidateHeaderFromStream(stream, type);
}
/// <summary>
/// Gets the native library version.
/// </summary>
/// <returns>Returns the native library version string.</returns>
public static string Version()
{
long size = Native.VersionSizeNative();
if (size < 0)
{
HandleError(size);
}
byte[] versionBytes = new byte[size];
long res = Native.VersionNative(versionBytes, (UIntPtr)versionBytes.Length);
if (res < 0)
{
HandleError(res);
}
return Encoding.UTF8.GetString(versionBytes);
}
/// <summary>
/// Method used to return the right exception depending on the error code.
/// </summary>
/// <param name="errorCode">The error code to handle.</param>
/// <returns>The exception matching the error code.</returns>
internal static DevolutionsCryptoException GetDevolutionsCryptoException(long errorCode)
{
if (Enum.IsDefined(typeof(NativeError), (int)errorCode))
{
return new DevolutionsCryptoException((NativeError)errorCode);
}
return new DevolutionsCryptoException(ManagedError.Error);
}
/// <summary>
/// Method used to throw the right exception depending on the error code.
/// </summary>
/// <param name="errorCode">The error code to handle.</param>
internal static void HandleError(long errorCode)
{
if (Enum.IsDefined(typeof(NativeError), (int)errorCode))
{
throw new DevolutionsCryptoException((NativeError)errorCode);
}
else
{
throw new DevolutionsCryptoException(ManagedError.Error);
}
}
}
}