This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathSecurePasswordBox.cs
More file actions
100 lines (89 loc) · 3.16 KB
/
Copy pathSecurePasswordBox.cs
File metadata and controls
100 lines (89 loc) · 3.16 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
using System.Diagnostics;
using System.Globalization;
using System.Windows.Controls;
namespace GitHub.UI
{
/// <summary>
/// More secure PasswordBox based on TextBox control
/// http://blogs.ugidotnet.org/leonardo
/// </summary>
public class SecurePasswordBox : PromptTextBox
{
// Fake char to display in Visual Tree
const char pwdChar = '●';
// flag used to bypass OnTextChanged
bool dirtyBaseText;
/// <summary>
/// Only copy of real password
/// </summary>
/// <remarks>
/// For more security use System.Security.SecureString type instead
/// </remarks>
string password = string.Empty;
/// <summary>
/// Provide access to base.Text without call OnTextChanged
/// </summary>
protected string BaseText
{
get { return base.Text; }
set
{
dirtyBaseText = true;
base.Text = value;
dirtyBaseText = false;
}
}
/// <summary>
/// Clean Password
/// </summary>
public new string Text
{
get { return password; }
set
{
password = value ?? string.Empty;
BaseText = new string(pwdChar, password.Length);
}
}
/// <summary>
/// TextChanged event handler for secure storing of password into Visual Tree,
/// text is replaced with pwdChar chars, clean text is kept in
/// Text property (CLR property not snoopable without mod)
/// </summary>
protected override void OnTextChanged(TextChangedEventArgs e)
{
if (dirtyBaseText)
return;
string currentText = BaseText;
int selStart = SelectionStart;
if (password != null && currentText.Length < password.Length)
{
// Remove deleted chars
password = password.Remove(selStart, password.Length - currentText.Length);
}
if (!string.IsNullOrEmpty(currentText))
{
for (int i = 0; i < currentText.Length; i++)
{
if (currentText[i] != pwdChar)
{
if (password == null)
{
throw new GitHubLogicException("Password can't be null here");
}
// Replace or insert char
string currentCharacter = currentText[i].ToString(CultureInfo.InvariantCulture);
password = BaseText.Length == password.Length ? password.Remove(i, 1).Insert(i, currentCharacter) : password.Insert(i, currentCharacter);
}
}
if (password == null)
{
throw new GitHubLogicException("Password can't be null here");
}
BaseText = new string(pwdChar, password.Length);
SelectionStart = selStart;
}
base.OnTextChanged(e);
}
}
}