This repository has been archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathForm1.cs
2255 lines (2076 loc) · 100 KB
/
Form1.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
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Timers;
namespace KeySAV2
{
public partial class Form1 : Form
{
public Form1()
{
FileSystemWatcher fsw = new FileSystemWatcher();
fsw.SynchronizingObject = this; // Timer Threading Related fix to cross-access control.
InitializeComponent();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
this.tab_Main.AllowDrop = true;
this.DragEnter += new DragEventHandler(tabMain_DragEnter);
this.DragDrop += new DragEventHandler(tabMain_DragDrop);
tab_Main.DragEnter += new DragEventHandler(tabMain_DragEnter);
tab_Main.DragDrop += new DragEventHandler(tabMain_DragDrop);
myTimer.Interval = 400; // milliseconds per trigger interval (0.4s)
myTimer.Start();
CB_Game.SelectedIndex = 0;
CB_MainLanguage.SelectedIndex = 0;
CB_BoxStart.SelectedIndex = 1;
changeboxsetting(null, null);
CB_BoxEnd.SelectedIndex = 0;
CB_BoxEnd.Enabled = false;
CB_Team.SelectedIndex = 0;
CB_ExportStyle.SelectedIndex = 0;
CB_BoxColor.SelectedIndex = 0;
CB_HP_Type.SelectedIndex = 0;
CB_No_IVs.SelectedIndex = 0;
toggleFilter(null, null);
loadINI();
this.FormClosing += onFormClose;
InitializeStrings();
}
// Drag & Drop Events //
private void tabMain_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
private void tabMain_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
string path = files[0]; // open first D&D
long len = new FileInfo(files[0]).Length;
if (len == 0x100000 || len == 0x10009C || len == 0x10019A)
{
tab_Main.SelectedIndex = 1;
openSAV(path);
}
else if (len == 28256)
{
tab_Main.SelectedIndex = 0;
openVID(path);
}
else MessageBox.Show("Dropped file is not supported.", "Error");
}
public void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
find3DS();
}
#region Global Variables
// Finding the 3DS SD Files
public bool pathfound = false;
public System.Timers.Timer myTimer = new System.Timers.Timer();
public static string path_exe = System.Windows.Forms.Application.StartupPath;
public static string datapath = path_exe + Path.DirectorySeparatorChar + "data";
public static string dbpath = path_exe + Path.DirectorySeparatorChar + "db";
public static string bakpath = path_exe + Path.DirectorySeparatorChar + "backup";
public string path_3DS = "";
public string path_POW = "";
// Language
public string[] natures;
public string[] types;
public string[] abilitylist;
public string[] movelist;
public string[] itemlist;
public string[] specieslist;
public string[] balls;
public string[] formlist;
public string[] vivlist;
// Blank File Egg Names
public string[] eggnames = { "タマゴ", "Egg", "Œuf", "Uovo", "Ei", "", "Huevo", "알" };
// Inputs
public byte[] savefile = new Byte[0x10009C];
public byte[] savkey = new Byte[0xB4AD4];
public byte[] batvideo = new Byte[0x100000]; // whatever
private byte[] zerobox = new Byte[232 * 30];
// Dumping Usage
public string vidpath = "";
public string savpath = "";
public string savkeypath = "";
public string vidkeypath = "";
public string custom1 = ""; public string custom2 = ""; public string custom3 = "";
public bool custom1b = false; public bool custom2b = false; public bool custom3b = false;
public string[] boxcolors = new string[] { "", "###", "####", "#####", "######" };
private string csvdata = "";
private string csvheader = "";
public int dumpedcounter = 0;
private int slots = 0;
public bool ghost = false;
private ushort[] selectedTSVs = new ushort[0];
// Breaking Usage
public string file1 = "";
public string file2 = "";
public string file3 = "";
public byte[] break1 = new Byte[0x10009C];
public byte[] break2 = new Byte[0x10009C];
public byte[] break3 = new Byte[0x10009C];
public byte[] video1 = new Byte[28256];
public byte[] video2 = new Byte[28256];
#endregion
// Utility
private void onFormClose(object sender, FormClosingEventArgs e)
{
// Save the ini file
saveINI();
}
private void loadINI()
{
try
{
// Detect startup path and data path.
if (!Directory.Exists(datapath)) // Create data path if it doesn't exist.
Directory.CreateDirectory(datapath);
if (!Directory.Exists(dbpath)) // Create db path if it doesn't exist.
Directory.CreateDirectory(dbpath);
if (!Directory.Exists(bakpath)) // Create backup path if it doesn't exist.
Directory.CreateDirectory(bakpath);
// Load .ini data.
if (!File.Exists(Path.Combine(datapath, "config.ini")))
File.Create(Path.Combine(datapath, "config.ini"));
else
{
TextReader tr = new StreamReader(Path.Combine(datapath, "config.ini"));
try
{
// Load the data
tab_Main.SelectedIndex = Convert.ToInt16(tr.ReadLine());
custom1 = tr.ReadLine();
custom2 = tr.ReadLine();
custom3 = tr.ReadLine();
custom1b = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
custom2b = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
custom3b = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
CB_ExportStyle.SelectedIndex = Convert.ToInt16(tr.ReadLine());
CB_MainLanguage.SelectedIndex = Convert.ToInt16(tr.ReadLine());
CB_Game.SelectedIndex = Convert.ToInt16(tr.ReadLine());
CHK_MarkFirst.Checked = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
CHK_Split.Checked = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
CHK_BoldIVs.Checked = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
CB_BoxColor.SelectedIndex = Convert.ToInt16(tr.ReadLine());
CHK_ColorBox.Checked = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
CHK_HideFirst.Checked = Convert.ToBoolean(Convert.ToInt16(tr.ReadLine()));
this.Height = Convert.ToInt16(tr.ReadLine());
this.Width = Convert.ToInt16(tr.ReadLine());
tr.Close();
}
catch
{
tr.Close();
}
}
}
catch (Exception e) { MessageBox.Show("Ini config file loading failed.\n\n" + e, "Error"); }
}
private void saveINI()
{
try
{
// Detect startup path and data path.
if (!Directory.Exists(datapath)) // Create data path if it doesn't exist.
Directory.CreateDirectory(datapath);
// Load .ini data.
if (!File.Exists(Path.Combine(datapath, "config.ini")))
File.Create(Path.Combine(datapath, "config.ini"));
else
{
TextWriter tr = new StreamWriter(Path.Combine(datapath, "config.ini"));
try
{
// Load the data
tr.WriteLine(tab_Main.SelectedIndex.ToString());
tr.WriteLine(custom1.ToString());
tr.WriteLine(custom2.ToString());
tr.WriteLine(custom3.ToString());
tr.WriteLine(Convert.ToInt16(custom1b).ToString());
tr.WriteLine(Convert.ToInt16(custom2b).ToString());
tr.WriteLine(Convert.ToInt16(custom3b).ToString());
tr.WriteLine(CB_ExportStyle.SelectedIndex.ToString());
tr.WriteLine(CB_MainLanguage.SelectedIndex.ToString());
tr.WriteLine(CB_Game.SelectedIndex.ToString());
tr.WriteLine(Convert.ToInt16(CHK_MarkFirst.Checked).ToString());
tr.WriteLine(Convert.ToInt16(CHK_Split.Checked).ToString());
tr.WriteLine(Convert.ToInt16(CHK_BoldIVs.Checked).ToString());
tr.WriteLine(CB_BoxColor.SelectedIndex.ToString());
tr.WriteLine(Convert.ToInt16(CHK_ColorBox.Checked).ToString());
tr.WriteLine(Convert.ToInt16(CHK_HideFirst.Checked).ToString());
tr.WriteLine(this.Height.ToString());
tr.WriteLine(this.Width.ToString());
tr.Close();
}
catch
{
tr.Close();
}
}
}
catch (Exception e) { MessageBox.Show("Ini config file saving failed.\n\n" + e, "Error"); }
}
public volatile int game;
// RNG
private static uint LCRNG(uint seed)
{
return (seed * 0x41C64E6D + 0x00006073) & 0xFFFFFFFF;
}
private static Random rand = new Random();
private static uint rnd32()
{
return (uint)(rand.Next(1 << 30)) << 2 | (uint)(rand.Next(1 << 2));
}
// PKX Struct Manipulation
private byte[] shuffleArray(byte[] pkx, uint sv)
{
byte[] ekx = new Byte[260]; Array.Copy(pkx, ekx, 8);
// Now to shuffle the blocks
// Define Shuffle Order Structure
var aloc = new byte[] { 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 2, 3, 1, 1, 2, 3, 2, 3, 1, 1, 2, 3, 2, 3 };
var bloc = new byte[] { 1, 1, 2, 3, 2, 3, 0, 0, 0, 0, 0, 0, 2, 3, 1, 1, 3, 2, 2, 3, 1, 1, 3, 2 };
var cloc = new byte[] { 2, 3, 1, 1, 3, 2, 2, 3, 1, 1, 3, 2, 0, 0, 0, 0, 0, 0, 3, 2, 3, 2, 1, 1 };
var dloc = new byte[] { 3, 2, 3, 2, 1, 1, 3, 2, 3, 2, 1, 1, 3, 2, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0 };
// Get Shuffle Order
var shlog = new byte[] { aloc[sv], bloc[sv], cloc[sv], dloc[sv] };
// UnShuffle Away!
for (int b = 0; b < 4; b++)
Array.Copy(pkx, 8 + 56 * shlog[b], ekx, 8 + 56 * b, 56);
// Fill the Battle Stats back
if (pkx.Length > 232)
Array.Copy(pkx, 232, ekx, 232, 28);
return ekx;
}
private byte[] decryptArray(byte[] ekx)
{
byte[] pkx = new Byte[0xE8]; Array.Copy(ekx, pkx, 0xE8);
uint pv = BitConverter.ToUInt32(pkx, 0);
uint sv = (((pv & 0x3E000) >> 0xD) % 24);
uint seed = pv;
// Decrypt Blocks with RNG Seed
for (int i = 8; i < 232; i += 2)
{
int pre = pkx[i] + ((pkx[i + 1]) << 8);
seed = LCRNG(seed);
int seedxor = (int)((seed) >> 16);
int post = (pre ^ seedxor);
pkx[i] = (byte)((post) & 0xFF);
pkx[i + 1] = (byte)(((post) >> 8) & 0xFF);
}
// Deshuffle
pkx = shuffleArray(pkx, sv);
return pkx;
}
private byte[] encryptArray(byte[] pkx)
{
// Shuffle
uint pv = BitConverter.ToUInt32(pkx, 0);
uint sv = (((pv & 0x3E000) >> 0xD) % 24);
byte[] ekxdata = new Byte[pkx.Length]; Array.Copy(pkx, ekxdata, pkx.Length);
// If I unshuffle 11 times, the 12th (decryption) will always decrypt to ABCD.
// 2 x 3 x 4 = 12 (possible unshuffle loops -> total iterations)
for (int i = 0; i < 11; i++)
ekxdata = shuffleArray(ekxdata, sv);
uint seed = pv;
// Encrypt Blocks with RNG Seed
for (int i = 8; i < 232; i += 2)
{
int pre = ekxdata[i] + ((ekxdata[i + 1]) << 8);
seed = LCRNG(seed);
int seedxor = (int)((seed) >> 16);
int post = (pre ^ seedxor);
ekxdata[i] = (byte)((post) & 0xFF);
ekxdata[i + 1] = (byte)(((post) >> 8) & 0xFF);
}
// Encrypt the Party Stats
seed = pv;
for (int i = 232; i < 260; i += 2)
{
int pre = ekxdata[i] + ((ekxdata[i + 1]) << 8);
seed = LCRNG(seed);
int seedxor = (int)((seed) >> 16);
int post = (pre ^ seedxor);
ekxdata[i] = (byte)((post) & 0xFF);
ekxdata[i + 1] = (byte)(((post) >> 8) & 0xFF);
}
// Done
return ekxdata;
}
private int getDloc(uint ec)
{
// Define Shuffle Order Structure
var dloc = new byte[] { 3, 2, 3, 2, 1, 1, 3, 2, 3, 2, 1, 1, 3, 2, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0 };
uint sv = (((ec & 0x3E000) >> 0xD) % 24);
return dloc[sv];
}
private bool verifyCHK(byte[] pkx)
{
ushort chk = 0;
for (int i = 8; i < 232; i += 2) // Loop through the entire PKX
chk += BitConverter.ToUInt16(pkx, i);
ushort actualsum = BitConverter.ToUInt16(pkx, 0x6);
if ((BitConverter.ToUInt16(pkx, 0x8) > 750) || (BitConverter.ToUInt16(pkx, 0x90) != 0))
return false;
return (chk == actualsum);
}
// File Type Loading
private void B_OpenSAV_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = savpath;
ofd.RestoreDirectory = true;
ofd.Filter = "SAV|*.sav;*.bin";
if (ofd.ShowDialog() == DialogResult.OK)
openSAV(ofd.FileName);
}
private void B_OpenVid_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = vidpath;
ofd.RestoreDirectory = true;
ofd.Filter = "Battle Video|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
openVID(ofd.FileName);
}
private void openSAV(string path)
{
openSAV_(path, ref savefile, ref savkeypath, true);
}
private void openSAV_(string path, ref byte[] savefile, ref string savkeypath, bool showUI)
{
// check to see if good input file
long len = new FileInfo(path).Length;
if (len != 0x100000 && len != 0x10009C && len != 0x10019A)
{
if(showUI) MessageBox.Show("Incorrect File Size");
return;
}
TB_SAV.Text = path;
// Go ahead and load the save file into RAM...
byte[] input = File.ReadAllBytes(path);
Array.Copy(input, input.Length % 0x100000, savefile, 0, 0x100000);
// Fetch Stamp
ulong stamp = BitConverter.ToUInt64(savefile, 0x10);
string keyfile = fetchKey(stamp, 0xB4AD4);
if (keyfile == "")
{
if (showUI)
{
L_KeySAV.Text = "Key not found. Please break for this SAV first.";
B_GoSAV.Enabled = false;
}
return;
}
else
{
if (showUI)
{
B_GoSAV.Enabled = true;
L_KeySAV.Text = new FileInfo(keyfile).Name;
}
savkeypath = keyfile;
}
if(showUI)
B_GoSAV.Enabled = CB_BoxEnd.Enabled = CB_BoxStart.Enabled = B_BKP_SAV.Visible = !(keyfile == "");
byte[] key = File.ReadAllBytes(keyfile);
byte[] empty = new Byte[232];
// Save file is already loaded.
// If slot one was used for the last save copy the boxes to slot 2 and apply key
if(BitConverter.ToUInt32(key, 0x80000) == BitConverter.ToUInt32(savefile, 0x168))
{
int boxoffset = BitConverter.ToInt32(key, 0x1C);
for(int i = 0, j = boxoffset; i<232*30*31; ++i, ++j)
{
savefile[j] = (byte)(savefile[j - 0x7F000] ^ key[0x80004 + i]);
}
}
// Get our empty file set up.
Array.Copy(key, 0x10, empty, 0xE0, 0x4);
string nick = eggnames[empty[0xE3] - 1];
// Stuff in the nickname to our blank EKX.
byte[] nicknamebytes = Encoding.Unicode.GetBytes(nick);
Array.Resize(ref nicknamebytes, 24);
Array.Copy(nicknamebytes, 0, empty, 0x40, nicknamebytes.Length);
// Fix CHK
uint chk = 0;
for (int i = 8; i < 232; i += 2) // Loop through the entire PKX
chk += BitConverter.ToUInt16(empty, i);
// Apply New Checksum
Array.Copy(BitConverter.GetBytes(chk), 0, empty, 06, 2);
empty = encryptArray(empty);
Array.Resize(ref empty, 0xE8);
scanSAV(savefile, key, empty, showUI);
File.WriteAllBytes(keyfile, key); // Key has been scanned for new slots, re-save key.
}
private void openVID(string path)
{
// check to see if good input file
B_GoBV.Enabled = CB_Team.Enabled = false;
long len = new FileInfo(path).Length;
if (len != 28256)
{ MessageBox.Show("Incorrect File Size"); return; }
TB_BV.Text = path;
// Go ahead and load the save file into RAM...
batvideo = File.ReadAllBytes(path);
// Fetch Stamp
ulong stamp = BitConverter.ToUInt64(batvideo, 0x10);
string keyfile = fetchKey(stamp, 0x1000);
B_GoBV.Enabled = CB_Team.Enabled = B_BKP_BV.Visible = (keyfile != "");
if (keyfile == "")
{ L_KeyBV.Text = "Key not found. Please break for this BV first."; return; }
else
{
string name = new FileInfo(keyfile).Name;
L_KeyBV.Text = "Key: " + name;
vidkeypath = keyfile;
}
// Check up on the key file...
CB_Team.Items.Clear();
CB_Team.Items.Add("My Team");
byte[] bvkey = File.ReadAllBytes(vidkeypath);
if (BitConverter.ToUInt64(bvkey, 0x800) != 0)
CB_Team.Items.Add("Enemy Team");
CB_Team.SelectedIndex = 0;
}
private string fetchKey(ulong stamp, int length)
{
// Find the Key in the datapath (program//data folder)
string[] files = Directory.GetFiles(datapath,"*.bin", SearchOption.AllDirectories);
byte[] data = new Byte[length];
for (int i = 0; i < files.Length; i++)
{
FileInfo fi = new FileInfo(files[i]);
{
if (fi.Length == length)
{
data = File.ReadAllBytes(files[i]);
ulong newstamp = BitConverter.ToUInt64(data, 0x0);
if (newstamp == stamp)
return files[i];
}
}
}
// else return nothing
return "";
}
// File Dumping
// SAV
private byte[] fetchpkx(byte[] input, byte[] keystream, int pkxoffset, int key1off, int key2off, byte[] blank)
{
// Auto updates the keystream when it dumps important data!
ghost = true;
byte[] ekx = new Byte[232];
byte[] key1 = new Byte[232]; Array.Copy(keystream, key1off, key1, 0, 232);
byte[] key2 = new Byte[232]; Array.Copy(keystream, key2off, key2, 0, 232);
byte[] encrypteddata = new Byte[232]; Array.Copy(input, pkxoffset, encrypteddata, 0, 232);
byte[] zeros = new Byte[232];
byte[] ezeros = encryptArray(zeros); Array.Resize(ref ezeros, 0xE8);
if (zeros.SequenceEqual(key1) && zeros.SequenceEqual(key2))
return null;
else if (zeros.SequenceEqual(key1))
{
// Key2 is confirmed to dump the data.
ekx = xortwos(key2, encrypteddata);
ghost = false;
}
else if (zeros.SequenceEqual(key2))
{
// Haven't dumped from this slot yet.
if (key1.SequenceEqual(encrypteddata))
{
// Slot hasn't changed.
return null;
}
else
{
// Try and decrypt the data...
ekx = xortwos(key1, encrypteddata);
if (verifyCHK(decryptArray(ekx)))
{
// Data has been dumped!
// Fill keystream data with our log.
Array.Copy(encrypteddata, 0, keystream, key2off, 232);
}
else
{
// Try xoring with the empty data.
if (verifyCHK(decryptArray(xortwos(ekx, blank))))
{
ekx = xortwos(ekx, blank);
Array.Copy(xortwos(encrypteddata, blank), 0, keystream, key2off, 232);
}
else if (verifyCHK(decryptArray(xortwos(ekx, ezeros))))
{
ekx = xortwos(ekx, ezeros);
Array.Copy(xortwos(encrypteddata, ezeros), 0, keystream, key2off, 232);
}
else return null; // Not a failed decryption; we just haven't seen new data here yet.
}
}
}
else
{
// We've dumped data at least once.
if (key1.SequenceEqual(encrypteddata) || key1.SequenceEqual(xortwos(encrypteddata,blank)) || key1.SequenceEqual(xortwos(encrypteddata,ezeros)))
{
// Data is back to break state, but we can still dump with the other key.
ekx = xortwos(key2, encrypteddata);
if (!verifyCHK(decryptArray(ekx)))
{
if (verifyCHK(decryptArray(xortwos(ekx, blank))))
{
ekx = xortwos(ekx, blank);
Array.Copy(xortwos(key2, blank), 0, keystream, key2off, 232);
}
else if (verifyCHK(decryptArray(xortwos(ekx, ezeros))))
{
// Key1 decrypts our data after we remove encrypted zeros.
// Copy Key1 to Key2, then zero out Key1.
ekx = xortwos(ekx, ezeros);
Array.Copy(xortwos(key2, ezeros), 0, keystream, key2off, 232);
}
else return null; // Decryption Error
}
}
else if (key2.SequenceEqual(encrypteddata) || key2.SequenceEqual(xortwos(encrypteddata, blank)) || key2.SequenceEqual(xortwos(encrypteddata, ezeros)))
{
// Data is changed only once to a dumpable, but we can still dump with the other key.
ekx = xortwos(key1, encrypteddata);
if (!verifyCHK(decryptArray(ekx)))
{
if (verifyCHK(decryptArray(xortwos(ekx, blank))))
{
ekx = xortwos(ekx, blank);
Array.Copy(xortwos(key1, blank), 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(ekx, ezeros))))
{
ekx = xortwos(ekx, ezeros);
Array.Copy(xortwos(key1, ezeros), 0, keystream, key1off, 232);
}
else return null; // Decryption Error
}
}
else
{
// Data has been observed to change twice! We can get our exact keystream now!
// Either Key1 or Key2 or Save is empty. Whichever one decrypts properly is the empty data.
// Oh boy... here we go...
ghost = false;
bool keydata1, keydata2 = false;
byte[] data1 = xortwos(encrypteddata, key1);
byte[] data2 = xortwos(encrypteddata, key2);
keydata1 =
(verifyCHK(decryptArray(data1))
||
verifyCHK(decryptArray(xortwos(data1, ezeros)))
||
verifyCHK(decryptArray(xortwos(data1, blank)))
);
keydata2 =
(verifyCHK(decryptArray(data2))
||
verifyCHK(decryptArray(xortwos(data2, ezeros)))
||
verifyCHK(decryptArray(xortwos(data2, blank)))
);
if (!keydata1 && !keydata2)
return null; // All 3 are occupied.
if (keydata1 && keydata2)
{
// Save file is currently empty...
// Copy key data from save file if it decrypts with Key1 data properly.
if (verifyCHK(decryptArray(data1)))
{
// No modifications necessary.
ekx = data1;
Array.Copy(encrypteddata, 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(data1, ezeros))))
{
ekx = ezeros;
Array.Copy(xortwos(encrypteddata,ezeros), 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(data1, blank))))
{
ekx = ezeros;
Array.Copy(xortwos(encrypteddata, blank), 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else return null; // unreachable
}
else if (keydata1) // Key 1 data is empty
{
if (verifyCHK(decryptArray(data1)))
{
ekx = data1;
Array.Copy(key1, 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(data1, ezeros))))
{
ekx = xortwos(data1, ezeros);
Array.Copy(xortwos(key1, ezeros), 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(data1, blank))))
{
ekx = xortwos(data1, blank);
Array.Copy(xortwos(key1, blank), 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else return null; // unreachable
}
else if (keydata2)
{
if (verifyCHK(decryptArray(data2)))
{
ekx = data2;
Array.Copy(key2, 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(data2, ezeros))))
{
ekx = xortwos(data2, ezeros);
Array.Copy(xortwos(key2, ezeros), 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else if (verifyCHK(decryptArray(xortwos(data2, blank))))
{
ekx = xortwos(data2, blank);
Array.Copy(xortwos(key2, blank), 0, keystream, key2off, 232);
Array.Copy(zeros, 0, keystream, key1off, 232);
}
else return null; // unreachable
}
}
}
byte[] pkx = decryptArray(ekx);
if (verifyCHK(pkx))
{
slots++;
return pkx;
}
else
return null; // Slot Decryption error?!
}
private void scanSAV(byte[] input, byte[] keystream, byte[] blank, bool showUI = true)
{
slots = 0;
int boxoffset = BitConverter.ToInt32(keystream, 0x1C);
for (int i = 0; i < 930; i++)
fetchpkx(input, keystream, boxoffset + i * 232, 0x100 + i * 232, 0x40000 + i * 232, blank);
if(showUI)
L_SAVStats.Text = String.Format("{0}/930", slots);
//MessageBox.Show("Unlocked: " + unlockedslots + " Soft: " + softslots);
}
private void dumpPKX_SAV(byte[] pkx, int dumpnum, int dumpstart)
{
if (ghost && CHK_HideFirst.Checked) return;
if (pkx == null || !verifyCHK(pkx)) //RTB_SAV.AppendText("SLOT LOCKED\n");
return;
Structures.PKX data = new Structures.PKX(pkx);
// Printout Parsing
if (data.species == 0) //RTB_SAV.AppendText("SLOT EMPTY");
return;
string box = "B"+(dumpstart + (dumpnum/30)).ToString("00");
string slot = (((dumpnum%30) / 6 + 1).ToString() + "," + (dumpnum % 6 + 1).ToString());
string species = specieslist[data.species];
string gender = data.genderstring;
string nature = natures[data.nature];
string ability = abilitylist[data.ability];
string hp = data.HP_IV.ToString();
string atk = data.ATK_IV.ToString();
string def = data.DEF_IV.ToString();
string spa = data.SPA_IV.ToString();
string spd = data.SPD_IV.ToString();
string spe = data.SPE_IV.ToString();
string hptype = types[data.hptype];
string ESV = data.ESV.ToString("0000");
string TSV = data.TSV.ToString("0000");
string ball = balls[data.ball];
string nickname = data.nicknamestr;
string otname = data.ot;
string TID = data.TID.ToString("00000");
string SID = data.SID.ToString("00000");
string move1 = movelist[data.move1];
string move2 = movelist[data.move2];
string move3 = movelist[data.move3];
string move4 = movelist[data.move4];
string ev_hp = data.HP_EV.ToString();
string ev_at = data.ATK_EV.ToString();
string ev_de = data.DEF_EV.ToString();
string ev_sa = data.SPA_EV.ToString();
string ev_sd = data.SPD_EV.ToString();
string ev_se = data.SPE_EV.ToString();
// Bonus
string relearn1 = movelist[data.eggmove1].ToString();
string relearn2 = movelist[data.eggmove2].ToString();
string relearn3 = movelist[data.eggmove3].ToString();
string relearn4 = movelist[data.eggmove4].ToString();
string isshiny = ""; if (data.isshiny) isshiny = "★";
string isegg = ""; if (data.isegg) isegg = "✓";
bool statisfiesFilters = true;
while (CHK_Enable_Filtering.Checked)
{
if (CHK_Egg.Checked && !data.isegg) { statisfiesFilters = false; break; }
bool checkHp = false;
if (CB_HP_Type.SelectedIndex > 0)
{
if (CB_HP_Type.SelectedIndex != data.hptype) { statisfiesFilters = false; break; }
checkHp = true;
}
int perfects = Convert.ToInt16(CB_No_IVs.SelectedItem);
bool ivsSelected = CHK_IV_HP.Checked || CHK_IV_Atk.Checked || CHK_IV_Def.Checked || CHK_IV_SpAtk.Checked || CHK_IV_SpDef.Checked || CHK_IV_Spe.Checked;
if (hp == "31" ||checkHp && hp == "30") --perfects;
else if (ivsSelected && CHK_IV_HP.Checked != RAD_IVs_Miss.Checked) { statisfiesFilters = false; break; }
if ((atk == "31" || checkHp && atk == "30") && !CHK_Special_Attacker.Checked || (atk == "0" || checkHp && atk == "1") && CHK_Special_Attacker.Checked) --perfects;
else if (ivsSelected && CHK_IV_Atk.Checked != RAD_IVs_Miss.Checked) { statisfiesFilters = false; break; }
if (def == "31" || checkHp && def == "30") --perfects;
else if (ivsSelected && CHK_IV_Def.Checked != RAD_IVs_Miss.Checked) { statisfiesFilters = false; break; }
if (spa == "31" || checkHp && spa == "30") --perfects;
else if (ivsSelected && CHK_IV_SpAtk.Checked != RAD_IVs_Miss.Checked) { statisfiesFilters = false; break; }
if (spd == "31" || checkHp && spd == "30") --perfects;
else if (ivsSelected && CHK_IV_SpDef.Checked != RAD_IVs_Miss.Checked) { statisfiesFilters = false; break; }
if ((spe == "31" || checkHp && spe == "30") && !CHK_Trickroom.Checked || (spe == "0" || checkHp && spe == "1") && CHK_Trickroom.Checked) --perfects;
else if (ivsSelected && CHK_IV_Spe.Checked != RAD_IVs_Miss.Checked) { statisfiesFilters = false; break; }
if (perfects > 0) { statisfiesFilters = false; break; }
if (CHK_Is_Shiny.Checked || CHK_Hatches_Shiny_For_Me.Checked || CHK_Hatches_Shiny_For.Checked)
{
// TODO: Should probably cache this somewhere...
if (!(CHK_Is_Shiny.Checked && data.isshiny ||
data.isegg && CHK_Hatches_Shiny_For_Me.Checked && ESV == TSV ||
data.isegg && CHK_Hatches_Shiny_For.Checked && Array.IndexOf(selectedTSVs, data.ESV) > -1))
{ statisfiesFilters = false; break; }
}
break;
}
if (statisfiesFilters)
{
if (!data.isegg) ESV = "";
// Vivillon Forms...
if (data.species >= 664 && data.species <= 666)
species += "-" + vivlist[data.altforms];
if (((CB_ExportStyle.SelectedIndex == 1 || CB_ExportStyle.SelectedIndex == 2 || (CB_ExportStyle.SelectedIndex != 0 && CB_ExportStyle.SelectedIndex < 6)) && CHK_BoldIVs.Checked))
{
if (hp == "31") hp = "**31**";
if (atk == "31") atk = "**31**";
if (def == "31") def = "**31**";
if (spa == "31") spa = "**31**";
if (spd == "31") spd = "**31**";
if (spe == "31") spe = "**31**";
}
string format = RTB_OPTIONS.Text;
if (CB_ExportStyle.SelectedIndex >= 6)
format = "{0} - {1} - {2} ({3}) - {4} - {5} - {6}.{7}.{8}.{9}.{10}.{11} - {12} - {13}";
if (CB_ExportStyle.SelectedIndex == 6)
{
csvdata += String.Format("{0},{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}\n",
box, slot, species, gender, nature, ability, hp, atk, def, spa, spd, spe, hptype, ESV, TSV, nickname, otname, ball, TID, SID, ev_hp, ev_at, ev_de, ev_sa, ev_sd, ev_se, move1, move2, move3, move4, relearn1, relearn2, relearn3, relearn4, isshiny, isegg);
}
if (CB_ExportStyle.SelectedIndex == 7)
{
isshiny = "";
if (data.isshiny)
isshiny = " ★";
if (data.isnick)
data.nicknamestr += String.Format(" ({0})", specieslist[data.species]);
string savedname =
data.species.ToString("000") + isshiny + " - "
+ data.nicknamestr + " - "
+ data.chk.ToString("X4") + data.EC.ToString("X8");
File.WriteAllBytes(Path.Combine(dbpath, CleanFileName(savedname) + ".pk6"), pkx);
}
if (!(CB_ExportStyle.SelectedIndex == 1 || CB_ExportStyle.SelectedIndex == 2 || (CB_ExportStyle.SelectedIndex != 0 && CB_ExportStyle.SelectedIndex < 6 && CHK_R_Table.Checked)))
{
if (ESV != "")
ESV = "[" + ESV + "]";
}
string result = String.Format(format, box, slot, species, gender, nature, ability, hp, atk, def, spa, spd, spe, hptype, ESV, TSV, nickname, otname, ball, TID, SID, ev_hp, ev_at, ev_de, ev_sa, ev_sd, ev_se, move1, move2, move3, move4, relearn1, relearn2, relearn3, relearn4, isshiny, isegg);
if (ghost && CHK_MarkFirst.Checked) result = "~" + result;
dumpedcounter++;
RTB_SAV.AppendText(result + "\n");
}
}
private void DumpSAV(object sender, EventArgs e)
{
csvheader = "Box,Row,Column,Species,Gender,Nature,Ability,HP IV,ATK IV,DEF IV,SPA IV,SPD IV,SPE IV,HP Type,ESV,TSV,Nickname,OT,Ball,TID,SID,HP EV,ATK EV,DEF EV,SPA EV,SPD EV,SPE EV,Move 1,Move 2,Move 3,Move 4,Relearn 1, Relearn 2, Relearn 3, Relearn 4, Shiny, Egg";
csvdata = csvheader + "\n";
RTB_SAV.Clear();
dumpedcounter = 0;
// Load our Keystream file.
byte[] keystream = File.ReadAllBytes(savkeypath);
byte[] empty = new Byte[232];
// Save file is already loaded.
// Get our empty file set up.
Array.Copy(keystream, 0x10, empty, 0xE0, 0x4);
string nick = eggnames[empty[0xE3] - 1];
// Stuff in the nickname to our blank EKX.
byte[] nicknamebytes = Encoding.Unicode.GetBytes(nick);
Array.Resize(ref nicknamebytes, 24);
Array.Copy(nicknamebytes, 0, empty, 0x40, nicknamebytes.Length);
// Fix CHK
uint chk = 0;
for (int i = 8; i < 232; i += 2) // Loop through the entire PKX
chk += BitConverter.ToUInt16(empty, i);
// Apply New Checksum
Array.Copy(BitConverter.GetBytes(chk), 0, empty, 06, 2);
empty = encryptArray(empty);
Array.Resize(ref empty, 0xE8);
// Get our dumping parameters.
int boxoffset = BitConverter.ToInt32(keystream, 0x1C);
int offset = 0;
int count = 30;
int boxstart = 1;
if (CB_BoxStart.Text == "All")
count = 30 * 31;
else
{
boxoffset += (Convert.ToInt16(CB_BoxStart.Text) - 1) * 30 * 232;
offset += (Convert.ToInt16(CB_BoxStart.Text) - 1) * 30 * 232;
count = (Convert.ToInt16(CB_BoxEnd.Text) - Convert.ToInt16(CB_BoxStart.Text) + 1) * 30;
boxstart = Convert.ToInt16(CB_BoxStart.Text);
}
// Get our TSVs for filtering
ushort tmp = 0;
selectedTSVs = (from val in Regex.Split(TB_SVs.Text, @"\s*[\s,;.]\s*") where UInt16.TryParse(val, out tmp) select tmp).ToArray();
string header = String.Format(RTB_OPTIONS.Text, "Box", "Slot", "Species", "Gender", "Nature", "Ability", "HP", "ATK", "DEF", "SPA", "SPD", "SPE", "HiddenPower", "ESV", "TSV", "Nick", "OT", "Ball", "TID", "SID", "HP EV", "ATK EV", "DEF EV", "SPA EV", "SPD EV", "SPE EV", "Move 1", "Move 2", "Move 3", "Move 4", "Relearn 1", "Relearn 2", "Relearn 3", "Relearn 4", "Shiny", "Egg");
if (CB_ExportStyle.SelectedIndex == 1 || CB_ExportStyle.SelectedIndex == 2 || (CB_ExportStyle.SelectedIndex != 0 && CB_ExportStyle.SelectedIndex < 6 && CHK_R_Table.Checked))
{
int args = Regex.Split(RTB_OPTIONS.Text, "{").Length;
header += "\n|";
for (int i = 0; i < args; i++)
header += ":---:|";
if (!CHK_Split.Checked) // Still append the header if we aren't doing it for every box.
{
// Add header if reddit
if (CHK_ColorBox.Checked)
{
if (CB_BoxColor.SelectedIndex == 0)
RTB_SAV.AppendText(boxcolors[1 + (rnd32() % 4)]);
else RTB_SAV.AppendText(boxcolors[CB_BoxColor.SelectedIndex - 1]);
}
// Append Box Name then Header
RTB_SAV.AppendText("B" + (boxstart).ToString("00") + "+\n\n");
RTB_SAV.AppendText(header + "\n");
}
}
for (int i = 0; i < count; i++)
{
if (i % 30 == 0 && CHK_Split.Checked)
{
RTB_SAV.AppendText("\n");
// Add box header
if ((CB_ExportStyle.SelectedIndex == 1 || CB_ExportStyle.SelectedIndex == 2 || ((CB_ExportStyle.SelectedIndex != 0 && CB_ExportStyle.SelectedIndex < 6)) && CHK_R_Table.Checked))
{
if (CHK_ColorBox.Checked)
{
// Add Reddit Coloring
if (CB_BoxColor.SelectedIndex == 0)
RTB_SAV.AppendText(boxcolors[1 + ((i / 30 + boxstart) % 4)]);
else RTB_SAV.AppendText(boxcolors[CB_BoxColor.SelectedIndex - 1]);
}
}
// Append Box Name then Header
RTB_SAV.AppendText("B" + (i / 30 + boxstart).ToString("00") + "\n\n");
RTB_SAV.AppendText(header + "\n");
}
byte[] pkx = fetchpkx(savefile, keystream, boxoffset + i * 232, 0x100 + offset + i * 232, 0x40000 + offset + i * 232, empty);
dumpPKX_SAV(pkx, i, boxstart);
}
// Copy Results to Clipboard
try { Clipboard.SetText(RTB_SAV.Text); }
catch { };
RTB_SAV.AppendText("\nData copied to clipboard!\nDumped: " + dumpedcounter);
RTB_SAV.Select(RTB_SAV.Text.Length - 1, 0);
RTB_SAV.ScrollToCaret();
if (CB_ExportStyle.SelectedIndex == 6)
{
SaveFileDialog savecsv = new SaveFileDialog();
savecsv.Filter = "Spreadsheet|*.csv";
savecsv.FileName = "KeySAV Data Dump.csv";
if (savecsv.ShowDialog() == DialogResult.OK)
System.IO.File.WriteAllText(savecsv.FileName, csvdata, Encoding.UTF8);
}
}
// BV
private void dumpPKX_BV(byte[] pkx, int slot)
{
if (pkx == null || !verifyCHK(pkx)) //RTB_SAV.AppendText("SLOT LOCKED\n");
return;
Structures.PKX data = new Structures.PKX(pkx);
// Printout Parsing
if (data.species == 0) //RTB_SAV.AppendText("SLOT EMPTY");
return;
string box = "~";
string species = specieslist[data.species];
string gender = data.genderstring;
string nature = natures[data.nature];
string ability = abilitylist[data.ability];
string hp = data.HP_IV.ToString();
string atk = data.ATK_IV.ToString();
string def = data.DEF_IV.ToString();
string spa = data.SPA_IV.ToString();
string spd = data.SPD_IV.ToString();