-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSecureData.cs
More file actions
126 lines (107 loc) · 3.46 KB
/
SecureData.cs
File metadata and controls
126 lines (107 loc) · 3.46 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
namespace WISecureData
{
public readonly struct SecureData : IDisposable
{
private readonly byte[] _bytes;
public SecureData(byte[] bytes)
{
_bytes = bytes ?? throw new ArgumentNullException(nameof(bytes));
}
// Convert SecureData to a byte array
public byte[] ConvertToBytes()
{
try
{
var copy = new byte[_bytes.Length];
Buffer.BlockCopy(_bytes, 0, copy, 0, _bytes.Length);
return copy;
}
catch
{
throw new Exception("Failed to Convert to Bytes.");
}
}
// Convert SecureData back to a string
public string ConvertToString()
{
try
{
return System.Text.Encoding.UTF8.GetString(_bytes);
}
catch
{
throw new Exception("Failed to Convert to String.");
}
}
// Convert a string to SecureData and securely clear the original string in memory
public static SecureData FromString(string value)
{
try
{
if (value == null)
throw new ArgumentNullException(nameof(value));
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(value);
// Securely clear the original string in memory
value.SecureClear();
return new SecureData(bytes);
}
catch
{
throw new Exception("Failed to Convert to SecureData.");
}
}
// Override ToString for base64 representation of the byte array
public override string ToString()
{
try
{
return Convert.ToBase64String(_bytes);
}
catch
{
throw new Exception("Failed to Convert SecureData to String.");
}
}
// Dispose to clear data in memory
public void Dispose()
{
try
{
if (_bytes != null)
Array.Clear(_bytes, 0, _bytes.Length); // Wipe the data
}
catch
{
throw new Exception("Failed to Dispose SecureData.");
}
}
// Equality check with constant-time comparison to avoid timing attacks
public static bool operator ==(SecureData left, SecureData right)
=> left.SecureCompare(right);
public static bool operator !=(SecureData left, SecureData right)
=> !left.SecureCompare(right);
public override bool Equals(object? obj)
=> obj is SecureData other && this == other;
public override int GetHashCode()
=> _bytes?.Length ?? 0;
// Constant-time comparison of SecureData objects
public bool SecureCompare(SecureData other)
{
try
{
if (other._bytes.Length != this._bytes.Length)
return false;
for (int i = 0; i < _bytes.Length; i++)
{
if (_bytes[i] != other._bytes[i])
return false;
}
return true;
}
catch
{
throw new Exception("Failed to Compare SecureData.");
}
}
}
}