-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathRMSecureString.cs
More file actions
671 lines (589 loc) · 27.6 KB
/
RMSecureString.cs
File metadata and controls
671 lines (589 loc) · 27.6 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
/*
RMLib: Nonvisual support classes used by multiple R&M Software programs
Copyright (C) Rick Parrish, R&M Software
This file is part of RMLib.
RMLib is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
RMLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with RMLib. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
namespace RandM.RMLib
{
public class RMSecureString : IDisposable
{
private bool _Disposed = false;
private SecureString _SecureString = null;
public RMSecureString()
{
_SecureString = new SecureString();
}
~RMSecureString()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!_Disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
// Note disposing has been done.
_Disposed = true;
}
}
/// <summary>
/// Creates RMSecureString object from plain text provided
/// Called for example when using:
/// RMSecureString rmss = "test";
/// </summary>
/// <param name="rhs">Plain text to initialize the RMSecureString to hold</param>
/// <returns>new RMSecureString</returns>
public static implicit operator RMSecureString(string rhs)
{
if (rhs == null) return null;
RMSecureString Result = new RMSecureString();
for (int i = 0; i < rhs.Length; i++)
{
Result.AppendChar(rhs[i]);
}
return Result;
}
/// <summary>
/// Creates RMSecureString object from RMSecureString provided
/// Called for example when using:
/// SecureString ss = new SecureString();
/// ss.AppendChar('x');
/// RMSecureString rmss = ss;
/// </summary>
/// <param name="rhs">RMSecureString to initialize the RMSecureString to hold</param>
/// <returns>new RMSecureString</returns>
public static implicit operator RMSecureString(SecureString rhs)
{
if (rhs == null) return null;
RMSecureString Result = new RMSecureString() {
_SecureString = rhs.Copy()
};
return Result;
}
public static bool operator ==(RMSecureString lhs, RMSecureString rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(RMSecureString lhs, RMSecureString rhs)
{
return !lhs.Equals(rhs);
}
public void AppendChar(char c)
{
_SecureString.AppendChar(c);
}
public void Clear()
{
_SecureString.Clear();
}
// Modified from http://social.msdn.microsoft.com/Forums/en-US/clr/thread/555a5cb6-790d-415d-b079-00d62b3a9632/
public override bool Equals(object rhs)
{
// Ensure we're comparing to another RMSecureString
if (!(rhs is RMSecureString)) return false;
// Easy check -- see if lengths differ
if (this.Length != ((RMSecureString)rhs).Length)
{
return false;
}
IntPtr bstr1 = IntPtr.Zero;
IntPtr bstr2 = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
bstr1 = Marshal.SecureStringToBSTR(_SecureString);
bstr2 = Marshal.SecureStringToBSTR(((RMSecureString)rhs)._SecureString);
unsafe
{
for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer(); *ptr1 != 0 && *ptr2 != 0; ++ptr1, ++ptr2)
{
if (*ptr1 != *ptr2)
{
return false;
}
}
}
return true;
}
finally
{
if (bstr1 != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(bstr1);
}
if (bstr2 != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(bstr2);
}
}
}
/// <summary>
/// Encrypt the current SecureString with the AES encryption algorithm, returning the computed value as a base64 string
/// </summary>
/// <returns>A base64 encoded string of the encrypted version of the current SecureString</returns>
/// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public string GetEncryptedString(RMSecureString password, int iterations = 32768)
{
string Result = "";
IntPtr PlainTextPtr = IntPtr.Zero;
IntPtr PasswordPtr = IntPtr.Zero;
try
{
// Get the secure plaintext string into a memory buffer
PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi(_SecureString);
int PlainTextSize = this.Length * sizeof(byte);
// Get the secure password string into a memory buffer
PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
int PasswordSize = password.Length * sizeof(byte);
// Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
unsafe
{
byte[] PlainTextBytes = new byte[PlainTextSize];
fixed (byte* ptr1 = PlainTextBytes)
{
byte[] PasswordBytes = new byte[PasswordSize];
fixed (byte* ptr2 = PasswordBytes)
{
try
{
Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);
// Get random bytes for salt
var RNG = new RNGCryptoServiceProvider();
byte[] SaltBytes = new byte[16];
RNG.GetBytes(SaltBytes);
// PBKDF2 key stretching
var DerivedPassword = new Rfc2898DeriveBytes(PasswordBytes, SaltBytes, iterations);
// Encryption with 128bit AES (using 192 or 256 bit isn't a good idea because Rfc2898DeriveBytes uses SHA-1, a 160 bit algorithm,
// so it's not recommended to take out more than 160 bits (increases time required to hash, but not time required to verify
// a hash, which means a defender does extra work but an attacker doesn't have to...Google it for reasons)
using (RijndaelManaged SymmetricKey = new RijndaelManaged()) {
SymmetricKey.GenerateIV();
SymmetricKey.Key = DerivedPassword.GetBytes(16);
SymmetricKey.Mode = CipherMode.CBC;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor())
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
Result = $"e!2!{iterations}!{Convert.ToBase64String(SaltBytes)}!{Convert.ToBase64String(SymmetricKey.IV)}!{Convert.ToBase64String(MemStream.ToArray())}";
}
}
}
}
}
finally
{
// Ensure managed array is cleared
Array.Clear(PlainTextBytes, 0, PlainTextSize);
// Ensure managed array is cleared
Array.Clear(PasswordBytes, 0, PasswordSize);
}
}
}
}
}
finally
{
// Ensure unmanaged memory is released.
if (PlainTextPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
}
// Ensure unmanaged memory is released.
if (PasswordPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
}
}
return Result;
}
public override int GetHashCode()
{
return _SecureString.GetHashCode();
}
/// <summary>
/// Hash the current SecureString with the SHA512 hash algorithm and saltBytes, returning the computed value as a base64 string
/// </summary>
/// <param name="saltBytes">The salt to apply to the hash</param>
/// <returns>A base64 encoded hash of the current SecureString</returns>
/// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
public string GetHashedString(byte[] saltBytes)
{
string Result = "";
IntPtr secureStringPtr = IntPtr.Zero;
try
{
// Get the secure string into a memory buffer
secureStringPtr = Marshal.SecureStringToGlobalAllocAnsi(_SecureString);
int stringSize = (saltBytes.Length + this.Length) * sizeof(byte);
// Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
unsafe
{
byte[] fixedByteArray = new byte[stringSize];
fixed (byte* ptr = fixedByteArray)
{
try
{
// Add the salt bytes
for (int i = 0; i < saltBytes.Length; i++) fixedByteArray[i] = saltBytes[i];
Marshal.Copy(secureStringPtr, fixedByteArray, saltBytes.Length, this.Length * sizeof(byte));
// Compute the hash
using (SHA512Managed SHA = new SHA512Managed())
{
Result = Convert.ToBase64String(SHA.ComputeHash(fixedByteArray));
}
}
finally
{
// Ensure managed array is cleared
Array.Clear(fixedByteArray, 0, stringSize);
}
}
}
}
finally
{
// Ensure unmanaged memory is released.
if (secureStringPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(secureStringPtr);
}
}
return Result;
}
public string GetPlainText()
{
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToBSTR(_SecureString);
return Marshal.PtrToStringAuto(unmanagedString);
}
finally
{
if (unmanagedString != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(unmanagedString);
}
}
}
/// <summary>
/// Encrypt the current SecureString with the ProtectData API, returning the computed value as a base64 string
/// </summary>
/// <returns>A base64 encoded string of the protected version of the current SecureString</returns>
/// <remarks>Based on the code from Sly Gryphon's comment at http://weblogs.asp.net/pglavich/archive/2006/10/29/Secure-TextBox-Updated.aspx </remarks>
public string GetProtectedString(RMSecureString password)
{
string Result = "";
IntPtr PlainTextPtr = IntPtr.Zero;
IntPtr PasswordPtr = IntPtr.Zero;
try
{
// Get the secure plaintext string into a memory buffer
PlainTextPtr = Marshal.SecureStringToGlobalAllocAnsi(_SecureString);
int PlainTextSize = this.Length * sizeof(byte);
// Get the secure password string into a memory buffer
PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
int PasswordSize = password.Length * sizeof(byte);
// Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
unsafe
{
byte[] PlainTextBytes = new byte[PlainTextSize];
fixed (byte* ptr1 = PlainTextBytes)
{
byte[] PasswordBytes = new byte[PasswordSize];
fixed (byte* ptr2 = PasswordBytes)
{
try
{
Marshal.Copy(PlainTextPtr, PlainTextBytes, 0, PlainTextSize);
Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);
if (PasswordSize == 0)
{
Result = "p" + Convert.ToBase64String(ProtectedData.Protect(PlainTextBytes, null, DataProtectionScope.CurrentUser));
}
else
{
Result = "p" + Convert.ToBase64String(ProtectedData.Protect(PlainTextBytes, PasswordBytes, DataProtectionScope.CurrentUser));
}
}
finally
{
// Ensure managed array is cleared
Array.Clear(PlainTextBytes, 0, PlainTextSize);
// Ensure managed array is cleared
Array.Clear(PasswordBytes, 0, PasswordSize);
}
}
}
}
}
finally
{
// Ensure unmanaged memory is released.
if (PlainTextPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(PlainTextPtr);
}
// Ensure unmanaged memory is released.
if (PasswordPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
}
}
return Result;
}
public SecureString GetSecureText()
{
return _SecureString;
}
public void InsertAt(int AIndex, char c)
{
_SecureString.InsertAt(AIndex, c);
}
public int Length
{
get
{
return _SecureString.Length;
}
}
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public void LoadFromEncryptedString(string encryptedString, RMSecureString password)
{
Clear();
if (encryptedString.StartsWith("p"))
{
LoadFromProtectedString(encryptedString, password);
}
else if (encryptedString.StartsWith("e!2!"))
{
LoadFromEncryptedStringv2(encryptedString, password);
}
else if (encryptedString.StartsWith("e"))
{
// Trim leading 'e', which is just an indicator to say that this is an encrypted and not a protected string
encryptedString = encryptedString.Substring(1);
IntPtr PasswordPtr = IntPtr.Zero;
try
{
// Get the secure password string into a memory buffer
PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
int PasswordSize = password.Length * sizeof(byte);
// Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
unsafe
{
byte[] Decrypted = null;
byte[] PasswordBytes = new byte[PasswordSize];
fixed (byte* ptr = PasswordBytes)
{
try
{
Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(PasswordBytes, Encoding.ASCII.GetBytes("RMSecureString"), "SHA512", 12345);
using (RijndaelManaged SymmetricKey = new RijndaelManaged())
{
SymmetricKey.Mode = CipherMode.CBC;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(DerivedPassword.GetBytes(32), DerivedPassword.GetBytes(16)))
{
using (MemoryStream MemStream = new MemoryStream(Convert.FromBase64String(encryptedString)))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
byte[] DecryptedByte = new byte[1];
int ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
while (ByteCount > 0)
{
_SecureString.AppendChar((char)DecryptedByte[0]);
ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
}
}
}
}
}
}
finally
{
// Ensure managed array is cleared
if (Decrypted != null) Array.Clear(Decrypted, 0, Decrypted.Length);
Array.Clear(PasswordBytes, 0, PasswordSize);
}
}
}
}
finally
{
// Ensure unmanaged memory is released.
if (PasswordPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
}
}
}
}
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
private void LoadFromEncryptedStringv2(string encryptedString, RMSecureString password) {
Clear();
// encryptedString is in the format e!2!{iterations}!{base64:salt}!{base64:iv}!{base64:encrypted_password}, so split it
string[] Pieces = encryptedString.Split('!');
int Iterations = int.Parse(Pieces[2]);
byte[] SaltBytes = Convert.FromBase64String(Pieces[3]);
byte[] IVBytes = Convert.FromBase64String(Pieces[4]);
encryptedString = Pieces[5];
IntPtr PasswordPtr = IntPtr.Zero;
try {
// Get the secure password string into a memory buffer
PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
int PasswordSize = password.Length * sizeof(byte);
// Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
unsafe {
byte[] Decrypted = null;
byte[] PasswordBytes = new byte[PasswordSize];
fixed (byte* ptr = PasswordBytes) {
try {
Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);
var DerivedPassword = new Rfc2898DeriveBytes(PasswordBytes, SaltBytes, Iterations);
using (RijndaelManaged SymmetricKey = new RijndaelManaged()) {
SymmetricKey.IV = IVBytes;
SymmetricKey.Key = DerivedPassword.GetBytes(16);
SymmetricKey.Mode = CipherMode.CBC;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor()) {
using (MemoryStream MemStream = new MemoryStream(Convert.FromBase64String(encryptedString))) {
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)) {
byte[] DecryptedByte = new byte[1];
int ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
while (ByteCount > 0) {
_SecureString.AppendChar((char)DecryptedByte[0]);
ByteCount = CryptoStream.Read(DecryptedByte, 0, 1);
}
}
}
}
}
} finally {
// Ensure managed array is cleared
if (Decrypted != null)
Array.Clear(Decrypted, 0, Decrypted.Length);
Array.Clear(PasswordBytes, 0, PasswordSize);
}
}
}
} finally {
// Ensure unmanaged memory is released.
if (PasswordPtr != IntPtr.Zero) {
Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
}
}
}
public void LoadFromProtectedString(string protectedString, RMSecureString password)
{
Clear();
if (protectedString.StartsWith("e"))
{
LoadFromEncryptedString(protectedString, password);
}
else if (protectedString.StartsWith("p"))
{
// Trim leading 'p', which is just an indicator to say that this is an encrypted and not a protected string
protectedString = protectedString.Substring(1);
IntPtr PasswordPtr = IntPtr.Zero;
try
{
// Get the secure password string into a memory buffer
PasswordPtr = Marshal.SecureStringToGlobalAllocAnsi(password.GetSecureText());
int PasswordSize = password.Length * sizeof(byte);
// Pin the array, copy data in, use it, and then make sure it is clear before unpinning.
unsafe
{
byte[] Decrypted = null;
byte[] PasswordBytes = new byte[PasswordSize];
fixed (byte* ptr = PasswordBytes)
{
try
{
Marshal.Copy(PasswordPtr, PasswordBytes, 0, PasswordSize);
if (PasswordSize == 0)
{
Decrypted = ProtectedData.Unprotect(Convert.FromBase64String(protectedString), null, DataProtectionScope.CurrentUser);
}
else
{
Decrypted = ProtectedData.Unprotect(Convert.FromBase64String(protectedString), PasswordBytes, DataProtectionScope.CurrentUser);
}
for (int i = 0; i < Decrypted.Length; i++)
{
_SecureString.AppendChar((char)Decrypted[i]);
}
}
finally
{
// Ensure managed array is cleared
if (Decrypted != null) Array.Clear(Decrypted, 0, Decrypted.Length);
Array.Clear(PasswordBytes, 0, PasswordSize);
}
}
}
}
finally
{
// Ensure unmanaged memory is released.
if (PasswordPtr != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocAnsi(PasswordPtr);
}
}
}
}
public void RemoveAt(int index)
{
_SecureString.RemoveAt(index);
}
public void SetAt(int index, char c)
{
_SecureString.SetAt(index, c);
}
}
}