-
Notifications
You must be signed in to change notification settings - Fork 386
/
Copy pathMaybeSecureString.cs
66 lines (55 loc) · 1.49 KB
/
MaybeSecureString.cs
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
using System;
using System.Security;
using System.Runtime.InteropServices;
namespace Docker.DotNet.BasicAuth
{
internal class MaybeSecureString : IDisposable
{
public SecureString Value { get; }
public MaybeSecureString(string str)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException(nameof(str));
}
var secureStr = new SecureString();
if (str.Length > 0)
{
foreach (char c in str)
{
secureStr.AppendChar(c);
}
}
Value = secureStr;
}
public MaybeSecureString(SecureString str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Value = str.Copy();
}
public void Dispose()
{
Value.Dispose();
}
public MaybeSecureString Copy()
{
return new MaybeSecureString(Value.Copy());
}
public override string ToString()
{
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(Value);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}
}
}