/
PermutateHash.xaml.cs
314 lines (277 loc) · 12 KB
/
PermutateHash.xaml.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace TPMPCRCalculator.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class PermutateHash : Page
{
private ApplicationDataContainer m_RoamingSettings = null;
private readonly NavigationHelper m_NavigationHelper;
private int m_CurrentAlgorithmIndex = 0;
private const string m_SettingSelectedHashAlgorithm = "permuterSelectedHash";
private const string m_SettingExpectedHash = "permuterExpectedHash";
private CancellationTokenSource cts;
public PermutateHash()
{
this.InitializeComponent();
this.m_RoamingSettings = ApplicationData.Current.RoamingSettings;
this.m_NavigationHelper = new NavigationHelper(this);
this.m_NavigationHelper.LoadState += LoadState;
this.m_NavigationHelper.SaveState += SaveState;
string[] algorithms = Worker.GetHashingAlgorithms();
ListOfAlgorithms.Items.Clear();
for (uint i = 0; i < algorithms.Length; i++)
{
ListOfAlgorithms.Items.Add(algorithms[i]);
}
ListOfAlgorithms.SelectedIndex = m_CurrentAlgorithmIndex;
Hashes.Items.Clear();
ResultHashes.Items.Clear();
}
private void MainPage_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
switch (e.Key)
{
case Windows.System.VirtualKey.Enter:
PermutateHashes_Click(sender, e);
break;
}
}
#region Save and Restore state
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>.
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void LoadState(object sender, LoadStateEventArgs e)
{
if (SuspensionManager.SessionState.ContainsKey(m_SettingSelectedHashAlgorithm))
{
int index;
if (Int32.TryParse((string)SuspensionManager.SessionState[m_SettingSelectedHashAlgorithm], out index))
{
if (index >= 0 && index < ListOfAlgorithms.Items.Count)
{
ListOfAlgorithms.SelectedIndex = index;
m_CurrentAlgorithmIndex = index;
}
}
}
if (SuspensionManager.SessionState.ContainsKey(m_SettingExpectedHash))
{
ExpectedResultHash.Text = (string)SuspensionManager.SessionState[m_SettingExpectedHash];
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/>.</param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void SaveState(object sender, SaveStateEventArgs e)
{
SuspensionManager.SessionState[m_SettingSelectedHashAlgorithm] = ListOfAlgorithms.SelectedIndex.ToString();
SuspensionManager.SessionState[m_SettingExpectedHash] = ExpectedResultHash.Text;
}
#endregion
#region NavigationHelper registration
/// <summary>
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
/// <para>
/// Page specific logic should be placed in event handlers for the
/// <see cref="NavigationHelper.LoadState"/>
/// and <see cref="NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
/// </para>
/// </summary>
/// <param name="e">Provides data for navigation methods and event
/// handlers that cannot cancel the navigation request.</param>
///
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.m_NavigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.m_NavigationHelper.OnNavigatedFrom(e);
}
#endregion
#region UI action handlers
private void AddHash_Click(object sender, RoutedEventArgs e)
{
ResultHashes.Items.Clear();
try
{
string hash = HashToAdd.Text.Trim();
Worker.ValidateIsHash((string)ListOfAlgorithms.SelectedItem, hash);
Hashes.Items.Add(hash);
HashToAdd.Text = "";
}
catch (Exception ex)
{
ResultHashes.Items.Add(ex.Message);
}
}
private void Reset_Click(object sender, RoutedEventArgs e)
{
Hashes.Items.Clear();
ResultHashes.Items.Clear();
ExpectedResultHash.Text = "";
HashToAdd.Text = "";
}
private async void PermutateHashes_Click(object sender, RoutedEventArgs e)
{
bool found = false;
ResultHashes.Items.Clear();
try
{
Worker.ValidateIsHash((string)ListOfAlgorithms.SelectedItem, ExpectedResultHash.Text.Trim());
cts = new CancellationTokenSource();
found = await CheckAndUpdateAsync(cts.Token);
}
catch (OperationCanceledException)
{
ResultHashes.Items.Add("Computation cancelled.");
}
catch (Exception ex)
{
if (string.IsNullOrEmpty(ex.Message))
{
ResultHashes.Items.Add("Computation failed.");
}
else
{
ResultHashes.Items.Add(ex.Message);
}
}
finally
{
// Set the CancellationTokenSource to null when the computation is complete.
cts = null;
if (!found)
ResultHashes.Items.Add("No order of the provided hashes resulted in the expected hash value.");
}
}
private void ListOfAlgorithms_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListOfAlgorithms.SelectedIndex != m_CurrentAlgorithmIndex)
{
m_CurrentAlgorithmIndex = ListOfAlgorithms.SelectedIndex;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}
#endregion
private async Task<List<string>> CheckAndUpdateAsync(string algorithm, int initialValue, string[] hashes, int[] permutation, string expectedResult)
{
if (hashes.Length != permutation.Length)
throw new ArgumentException("Hash array and permutation array have different size.");
return await Task<List<string>>.Run(() =>
{
// resort hashes into order of permutation
string[] permutatedHashes = new string[hashes.Length];
for (int i = 0; i < hashes.Length; i++)
{
permutatedHashes[i] = hashes[permutation[i]];
}
int index = Worker.CheckIfRightHashOrder(algorithm, initialValue, permutatedHashes, expectedResult);
if (index >= 0)
{
List<string> result = new List<string>(index + 2);
result.Add(Worker.GetZeroDigestForAlgorithm(algorithm, initialValue));
for (int i = 0; i <= index; i++)
{
result.Add((string)hashes[i]);
}
return result;
}
return new List<string>();
});
}
private async Task<bool> CheckAndUpdateAsync(CancellationToken ct)
{
if (Hashes.Items.Count == 0)
return false;
int[] singlePermutation = new int[Hashes.Items.Count];
for (int i = 0; i < Hashes.Items.Count; i++)
singlePermutation[i] = i;
IEnumerable<IEnumerable<int>> permutations;
if (DontChangeHashOrder.IsChecked.Value)
{
permutations = new List<IEnumerable<int>>(1);
List<IEnumerable<int>> single = permutations as List<IEnumerable<int>>;
single.Add(singlePermutation);
}
else
{
permutations = PermutationHelper.GetPermutations<int>(singlePermutation, singlePermutation.Length);
}
// split the permuations into chunks that we run sequenctially to avoid out of memory exception when trying to
// run too many permutations in parallel
var chunks = PermutationHelper.Split<IEnumerable<int>>(permutations, 1024);
bool foundMatch = false;
List<string> results = new List<string>();
// check localities (0..4) and Locality Indicator (locality as bitfield) (1, 2, 4, 8, 16)
int[] startValues = new int[] { 0, 1, 2, 3, 4, 8, 16 };
foreach (int startValue in startValues)
{
foreach (var chunk in chunks)
{
IEnumerable<Task<List<string>>> computePermutatioQuery =
from permutation in chunk select CheckAndUpdateAsync((string)ListOfAlgorithms.SelectedItem, startValue, Hashes.Items.Cast<string>().ToArray<string>(), permutation.ToArray<int>(), ExpectedResultHash.Text.Trim());
List<Task<List<string>>> computePermutation = computePermutatioQuery.ToList();
while (computePermutation.Count > 0)
{
Task<List<string>> finishedPermutation = await Task.WhenAny(computePermutation);
computePermutation.Remove(finishedPermutation);
results = await finishedPermutation;
foundMatch = results.Count > 0;
if (foundMatch || ct.IsCancellationRequested)
{
// cancel the rest
cts.Cancel();
break;
}
}
if (foundMatch || ct.IsCancellationRequested)
break;
}
if (foundMatch || ct.IsCancellationRequested)
break;
}
if (foundMatch)
{
foreach (string result in results)
{
ResultHashes.Items.Add(result);
}
}
return foundMatch;
}
}
}