-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMainWindow.xaml.cs
2052 lines (1923 loc) · 79.9 KB
/
MainWindow.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
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.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using Org.BouncyCastle.Crypto.Digests;
using System.ComponentModel;
namespace Crypto_Tool
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
byte[] global_iv = null;
bool is_fromfile = false;
Stream Hash_stream = null;
byte[] hash_res = null;
public static object locker = new object();
private readonly BackgroundWorker _BGdWorker_md5 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha1 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha2_224 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha2_256 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha2_384 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha2_512 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha3_224 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha3_256 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha3_384 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sha3_512 = new BackgroundWorker();
private readonly BackgroundWorker _BGdWorker_sm3 = new BackgroundWorker();
#region SM2
//国密标准256位曲线参数
BigInteger SM2_ECC_P = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);
BigInteger SM2_ECC_A = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16);
BigInteger SM2_ECC_B = new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16);
BigInteger SM2_ECC_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);
BigInteger SM2_ECC_H = BigInteger.One;
BigInteger SM2_ECC_GX = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16);
BigInteger SM2_ECC_GY = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16);
public MainWindow()
{
InitializeComponent();
_BGdWorker_md5.DoWork += new DoWorkEventHandler(Md5_dowork);
_BGdWorker_md5.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Md5_work_completed);
//_BGdWorker_md5.ProgressChanged += new ProgressChangedEventHandler(Md5_work_ProgressChanged);
_BGdWorker_sha1.DoWork += new DoWorkEventHandler(Sha1_dowork);
_BGdWorker_sha1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha1_work_completed);
_BGdWorker_sha2_224.DoWork += new DoWorkEventHandler(Sha2_224_dowork);
_BGdWorker_sha2_224.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha2_224_work_completed);
_BGdWorker_sha2_256.DoWork += new DoWorkEventHandler(Sha2_256_dowork);
_BGdWorker_sha2_256.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha2_256_work_completed);
_BGdWorker_sha2_384.DoWork += new DoWorkEventHandler(Sha2_384_dowork);
_BGdWorker_sha2_384.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha2_384_work_completed);
_BGdWorker_sha2_512.DoWork += new DoWorkEventHandler(Sha2_512_dowork);
_BGdWorker_sha2_512.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha2_512_work_completed);
_BGdWorker_sha3_224.DoWork += new DoWorkEventHandler(Sha3_224_dowork);
_BGdWorker_sha3_224.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha3_224_work_completed);
_BGdWorker_sha3_256.DoWork += new DoWorkEventHandler(Sha3_256_dowork);
_BGdWorker_sha3_256.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha3_256_work_completed);
_BGdWorker_sha3_384.DoWork += new DoWorkEventHandler(Sha3_384_dowork);
_BGdWorker_sha3_384.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha3_384_work_completed);
_BGdWorker_sha3_512.DoWork += new DoWorkEventHandler(Sha3_512_dowork);
_BGdWorker_sha3_512.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sha3_512_work_completed);
_BGdWorker_sm3.DoWork += new DoWorkEventHandler(Sm3_dowork);
_BGdWorker_sm3.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Sm3_work_completed);
//计算杂凑时,默认选中的项
cb_filesize.IsChecked = true;
cb_mdtime.IsChecked = true;
cb_toUpper.IsChecked = true;
cb_md5.IsChecked = true;
cb_sha1.IsChecked = true;
cb_sha2_256.IsChecked = true;
//cb_sha2_512.IsChecked = true;
cb_sm3.IsChecked = true;
}
/// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_selfile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "选择待加密的文件";
op.DefaultExt = ".txt";
op.Filter = "All files|*.*";
if (op.ShowDialog() == true)
{
tb_filepath.Clear();
tb_filepath.Text = op.FileName;
tb_input.Clear();
}
op.FilterIndex = 0;
op.CheckFileExists = true;
op.CheckPathExists = true;
}
private void tb_filepath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
private void tb_filepath_PreviewDrop(object sender, DragEventArgs e)
{
string[] data = (string[])e.Data.GetData(DataFormats.FileDrop);
if (data == null || data.Length < 1)
{
return;
}
else
{
tb_filepath.Clear();//清空
tb_filepath.Text = data[0];
tb_input.Clear();
}
}
/// <summary>
/// 生成公私钥对
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_genkey_Click(object sender, RoutedEventArgs e)
{
ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
ECKeyGenerationParameters aKeyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom());
keyPairGenerator.Init(aKeyGenParams);
AsymmetricCipherKeyPair aKp = keyPairGenerator.GenerateKeyPair();
ECPublicKeyParameters aPub = (ECPublicKeyParameters)aKp.Public;
ECPrivateKeyParameters aPriv = (ECPrivateKeyParameters)aKp.Private;
BigInteger privateKey = aPriv.D;
ECPoint publicKey = aPub.Q;
byte[] pubkey = Hex.Encode(publicKey.GetEncoded());
string temp_pubkey = Encoding.UTF8.GetString(pubkey).ToUpper();
tb_pubinfo.Text = temp_pubkey;
MessageBox.Show("下一步:保存公钥", "提示");
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存公钥";
sfd.Filter = "All files|*.pub";
if (sfd.ShowDialog() == true)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
fs.Write(pubkey, 0, pubkey.Length);
fs.Close();
MessageBox.Show("已成功保存公钥至" + sfd.FileName, "提示");
}
else
{
MessageBox.Show("请保存公钥到文件!!", "提示");
}
string temp_prikey = Encoding.UTF8.GetString(Hex.Encode(privateKey.ToByteArray())).ToUpper();
tb_priInfo.Text = temp_prikey;
byte[] prikey = Encoding.UTF8.GetBytes(temp_prikey);
MessageBox.Show("下一步:保存私钥", "提示");
SaveFileDialog sfd1 = new SaveFileDialog();
sfd1.Title = "保存私钥";
sfd1.Filter = "All files|*.pri";
if (sfd1.ShowDialog() == true)
{
FileStream fs = new FileStream(sfd1.FileName, FileMode.Create, FileAccess.Write);
fs.Write(prikey, 0, prikey.Length);
fs.Close();
MessageBox.Show("已成功保存私钥至" + sfd1.FileName, "提示");
}
else
{
MessageBox.Show("请保存私钥到文件!!", "提示");
return;
}
}
/// <summary>
/// 加密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_en_Click(object sender, RoutedEventArgs e)
{
if (tb_filepath.Text == string.Empty && tb_input.Text == string.Empty)
{
MessageBox.Show("请选择待加密的文件或者输入数据!!", "提示");
return;
}
else
{
byte[] bytedata, tmpdata = null;
if (tb_input.Text == string.Empty && tb_filepath.Text != string.Empty)
{
//tmpdata = FiletoByte(tb_filepath.Text);
tmpdata = File.ReadAllBytes(tb_filepath.Text);
}
else if (tb_input.Text != string.Empty && tb_filepath.Text == string.Empty)
{
tmpdata = Encoding.UTF8.GetBytes(tb_input.Text);
}
bytedata = tmpdata;
Stopwatch watch = new Stopwatch();
if (tb_pubinfo.Text == string.Empty)
{
MessageBox.Show("请生成密钥对或导入公钥!!", "提示");
return;
}
string pubkey = tb_pubinfo.Text;
watch.Start();
string ciphertext = Encrypt(Hex.Decode(pubkey), bytedata);
watch.Stop();
tb_en.Clear();
tb_en.Text = "加密耗时:" + watch.ElapsedMilliseconds.ToString() + "ms(毫秒)";
byte[] cipher_bytedata = Encoding.UTF8.GetBytes(ciphertext);
tb_res.Clear();
tb_res.AppendText(ciphertext);
if (tb_input.Text == string.Empty && tb_filepath.Text != string.Empty)
{
string extension = System.IO.Path.GetExtension(tb_filepath.Text);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存加密文件";
sfd.Filter = "All files|*" + extension;
if (sfd.ShowDialog() == true)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
fs.Write(cipher_bytedata, 0, cipher_bytedata.Length);
tb_en.AppendText(" 加密文件路径:" + sfd.FileName);
fs.Close();
MessageBox.Show("已成功加密文件!!", "提示");
}
else
{
MessageBox.Show("请保存密文文件!!", "提示");
return;
}
}
}
}
/// <summary>
/// 解密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_de_Click(object sender, RoutedEventArgs e)
{
string extension = null;
string encrypt_bytedata = null;
if (tb_input.Text == string.Empty)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "选择待解密的文件";
op.DefaultExt = ".txt";
op.Filter = "All files|*.*";
if (op.ShowDialog() == true)
{
string temp_path = op.FileName;
extension = System.IO.Path.GetExtension(temp_path);
//MessageBox.Show(temp_path);
//byte[] temp_encrypt_bytedata = FiletoByte(temp_path);
byte[] temp_encrypt_bytedata = File.ReadAllBytes(temp_path);
encrypt_bytedata = Encoding.Default.GetString(temp_encrypt_bytedata);
}
else
{
MessageBox.Show("请选择待解密的文件", "提示");
return;
}
}
else
{
byte[] tmp = Encoding.UTF8.GetBytes(tb_input.Text);
if (tmp.Length <= 97)
{
MessageBox.Show("请检查密文是否正确", "错误");
return;
}
else
{
encrypt_bytedata = Encoding.UTF8.GetString(tmp);
}
}
Stopwatch watch = new Stopwatch();
if (tb_priInfo.Text == string.Empty)
{
MessageBox.Show("请生成密钥对或导入私钥!!", "提示");
return;
}
string prikey = tb_priInfo.Text.ToUpper();
watch.Start();
byte[] plain_bytedata = Decrypt(Hex.Decode(prikey), Hex.Decode(encrypt_bytedata));
watch.Stop();
tb_de.Clear();
tb_de.Text = "解密耗时:" + watch.ElapsedMilliseconds.ToString() + "ms(毫秒)";
if (tb_input.Text == string.Empty)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存解密文件";
sfd.Filter = "All files|*" + extension;
if (sfd.ShowDialog() == true)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
fs.Write(plain_bytedata, 0, plain_bytedata.Length);
tb_de.AppendText("解密文件路径:" + sfd.FileName);
fs.Close();
MessageBox.Show("已成功解密文件!!", "提示");
}
else
{
MessageBox.Show("请保存解密文件", "提示");
return;
}
}
else
{
tb_res.Clear();
tb_res.AppendText(Encoding.UTF8.GetString(plain_bytedata));
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_inpub_Click(object sender, RoutedEventArgs e)
{
tb_pubinfo.Clear();//清空
OpenFileDialog op = new OpenFileDialog();
op.Title = "导入公钥";
op.DefaultExt = ".pub";
op.Filter = "All files|*.pub";
if (op.ShowDialog() == true)
{
string temp_path = op.FileName;
//byte[] temp_pubkey = FiletoByte(temp_path);
byte[] temp_pubkey = File.ReadAllBytes(temp_path);
string pubkey = Encoding.Default.GetString(temp_pubkey).ToUpper();
tb_pubinfo.Text = pubkey;
}
else
{
MessageBox.Show("请选择存储公钥的文件", "提示");
return;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_inpri_Click(object sender, RoutedEventArgs e)
{
tb_priInfo.Clear();//清空
OpenFileDialog op = new OpenFileDialog();
op.Title = "导入私钥";
op.DefaultExt = ".pri";
op.Filter = "All files|*.pri";
if (op.ShowDialog() == true)
{
string temp_path = op.FileName;
//byte[] temp_prikey = FiletoByte(temp_path);
byte[] temp_prikey = File.ReadAllBytes(temp_path);
string prikey = Encoding.Default.GetString(temp_prikey).ToUpper();
tb_priInfo.Text = prikey;
}
else
{
MessageBox.Show("请选择存储私钥的文件", "提示");
return;
}
}
#region 自定义函数
/// <summary>
/// 加密函数
/// </summary>
/// <param name="publicKey"></param>
/// <param name="data"></param>
/// <returns></returns>
public string Encrypt(byte[] publicKey, byte[] data)
{
if (null == publicKey || publicKey.Length == 0)
{
return null;
}
if (data == null || data.Length == 0)
{
return null;
}
byte[] source = new byte[data.Length];
Array.Copy(data, 0, source, 0, data.Length);
ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
ECPoint userkey = curve.DecodePoint(publicKey);
ECPublicKeyParameters aPub = new ECPublicKeyParameters(userkey, domainParams);
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true, new ParametersWithRandom(aPub));
byte[] enc = sm2Engine.ProcessBlock(source, 0, source.Length);
return Encoding.Default.GetString(Hex.Encode(enc));
}
/// <summary>
/// 解密函数
/// </summary>
/// <param name="privateKey"></param>
/// <param name="encryptedData"></param>
/// <returns></returns>
public byte[] Decrypt(byte[] privateKey, byte[] encryptedData)
{
if (null == privateKey || privateKey.Length == 0)
{
return null;
}
if (encryptedData == null || encryptedData.Length == 0)
{
return null;
}
byte[] enc = new byte[encryptedData.Length];
Array.Copy(encryptedData, 0, enc, 0, encryptedData.Length);
BigInteger userD = new BigInteger(1, privateKey);
ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
ECPrivateKeyParameters aPriv = new ECPrivateKeyParameters(userD, domainParams);
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, aPriv);
byte[] dec = sm2Engine.ProcessBlock(enc, 0, enc.Length);
return dec;
}
/// <summary>
/// 文件转换成字节数组
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
//private byte[] FiletoByte(string path)
//{
// FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
// try
// {
// byte[] databytes = new byte[fs.Length];
// fs.Read(databytes, 0, (int)fs.Length);
// return databytes;
// }
// catch (Exception)
// {
// return null;
// }
// finally
// {
// if (fs != null)
// {
// fs.Close();
// }
// }
//}
#endregion
#endregion
#region SM4
//选择文件
private void bt_selfile_sm4_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "选择待加密的文件";
op.DefaultExt = ".txt";
op.Filter = "All files|*.*";
if (op.ShowDialog() == true)
{
tb_filepath_sm4.Clear();
tb_filepath_sm4.Text = op.FileName;
tb_input_sm4.Clear();
}
op.FilterIndex = 0;
op.CheckFileExists = true;
op.CheckPathExists = true;
}
private void tb_sy_PreviewDragOver(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
private void tb_filepath_sm4_PreviewDrop(object sender, DragEventArgs e)
{
string[] data = (string[])e.Data.GetData(DataFormats.FileDrop);
if (data == null || data.Length < 1)
{
return;
}
else
{
tb_filepath_sm4.Clear();//清空
tb_filepath_sm4.Text = data[0];
tb_input_sm4.Clear();
}
}
/// <summary>
/// 加密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_en_sm4_Click(object sender, RoutedEventArgs e)
{
if (tb_filepath_sm4.Text == string.Empty && tb_input_sm4.Text == string.Empty)
{
MessageBox.Show("请选择待加密的文件或者输入数据!!", "提示");
return;
}
else
{
byte[] bytedata, tmpdata = null;
if (tb_input_sm4.Text == string.Empty && tb_filepath_sm4.Text != string.Empty)
{
tmpdata = File.ReadAllBytes(tb_filepath_sm4.Text);
}
else if (tb_input_sm4.Text != string.Empty && tb_filepath_sm4.Text == string.Empty)
{
tmpdata = Encoding.UTF8.GetBytes(tb_input_sm4.Text);
}
bytedata = tmpdata;
if (tb_key.Text == string.Empty)
{
MessageBox.Show("请输入密钥!!", "提示");
return;
}
tb_res_sm4.Clear();
tb_eninfo_sm4.Clear();
string tmp_key = tb_key.Text;
byte[] key_tmp = Encoding.Default.GetBytes(tmp_key);
byte[] digest;
SM3Digest md = new SM3Digest();
md.BlockUpdate(key_tmp, 0, key_tmp.Length);
digest = new byte[md.GetDigestSize()];
md.DoFinal(digest, 0);
string hex = Encoding.Default.GetString(Hex.Encode(digest));
string key_temp = hex.Substring(0, 32);
byte[] keybytes = Hex.Decode(key_temp);
byte[] cipher, hex_cipher = null, iv = null;
//Stopwatch watch = new Stopwatch();
//watch.Reset();
if (rb_ecb.IsChecked == true)//ECB模式
{
//watch.Start();
//DateTime beforDT = DateTime.Now;
cipher = sm4_encrypt(bytedata, keybytes, "ECB", null);
//DateTime afterDT = DateTime.Now;
//watch.Stop();
//time = watch.ElapsedMilliseconds;
//TimeSpan ts = afterDT.Subtract(beforDT);
//time = ts.TotalMilliseconds;
hex_cipher = Hex.Encode(cipher);
//string str_cipher = Encoding.UTF8.GetString(hex_cipher);
}
else if (rb_cbc.IsChecked == true)//CBC模式
{
iv = geniv();
global_iv = iv;
tb_iv.Text = Encoding.UTF8.GetString(global_iv);
cipher = sm4_encrypt(bytedata, keybytes, "CBC", iv);
hex_cipher = Hex.Encode(cipher);
//string str_cipher = Encoding.UTF8.GetString(hex_cipher);
}
else if (rb_cfb.IsChecked == true)//CFB模式
{
iv = geniv();
global_iv = iv;
tb_iv.Text = Encoding.UTF8.GetString(global_iv);
cipher = sm4_encrypt(bytedata, keybytes, "CFB", iv);
hex_cipher = Hex.Encode(cipher);
//string str_cipher = Encoding.UTF8.GetString(hex_cipher);
}
else if (rb_ofb.IsChecked == true)//OFB模式
{
iv = geniv();
global_iv = iv;
tb_iv.Text = Encoding.UTF8.GetString(global_iv);
cipher = sm4_encrypt(bytedata, keybytes, "OFB", iv);
hex_cipher = Hex.Encode(cipher);
//string str_cipher = Encoding.UTF8.GetString(hex_cipher);
}
else if (rb_ctr.IsChecked == true)//CTR模式
{
iv = geniv();
global_iv = iv;
tb_iv.Text = Encoding.UTF8.GetString(global_iv);
cipher = sm4_encrypt(bytedata, keybytes, "CTR", iv);
hex_cipher = Hex.Encode(cipher);
//string str_cipher = Encoding.UTF8.GetString(hex_cipher);
}
else
{
MessageBox.Show("请选择加密模式!!", "提示");
return;
}
if (hex_cipher != null)
{
string str_cipher = Encoding.UTF8.GetString(hex_cipher);
if (global_iv != null)
{
string str_iv = Encoding.UTF8.GetString(global_iv);
byte[] hex_iv_cipher = Encoding.UTF8.GetBytes(str_iv + str_cipher);
hex_cipher = hex_iv_cipher;
}
tb_res.Clear();
tb_res_sm4.AppendText(str_cipher);
if (tb_input_sm4.Text == string.Empty && tb_filepath_sm4.Text != string.Empty)
{
string extension = System.IO.Path.GetExtension(tb_filepath_sm4.Text);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存加密文件";
sfd.Filter = "All files|*" + extension;
if (sfd.ShowDialog() == true)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
fs.Write(hex_cipher, 0, hex_cipher.Length);
tb_eninfo_sm4.AppendText(" 加密文件路径:" + sfd.FileName);
fs.Close();
MessageBox.Show("已成功加密文件!!", "提示");
}
else
{
MessageBox.Show("请保存密文文件!!", "提示");
return;
}
}
else if (tb_input_sm4.Text != string.Empty && tb_filepath_sm4.Text == string.Empty)
{
tb_eninfo_sm4.Text = "加密完成,详见运算结果";
}
}
else
{
return;
}
}
}
/// <summary>
/// 解密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bt_de_sm4_Click(object sender, RoutedEventArgs e)
{
if (tb_filepath_sm4.Text == string.Empty && tb_input_sm4.Text == string.Empty)
{
MessageBox.Show("请选择待解密的文件或者输入数据!!", "提示");
return;
}
else
{
byte[] bytedata = null, bytedata_de = null, datafrominput = null;
if (tb_input_sm4.Text == string.Empty && tb_filepath_sm4.Text != string.Empty)
{
bytedata = File.ReadAllBytes(tb_filepath_sm4.Text);
try
{
bytedata_de = Hex.Decode(bytedata);
}
catch (Exception)
{
MessageBox.Show("密文格式不正确!!", "提示");
return;
}
is_fromfile = true;
}
else if (tb_input_sm4.Text != string.Empty && tb_filepath_sm4.Text == string.Empty)
{
datafrominput = Encoding.UTF8.GetBytes(tb_input_sm4.Text);
try
{
bytedata_de = Hex.Decode(datafrominput);
}
catch (Exception)
{
MessageBox.Show("密文格式不正确!!", "提示");
return;
}
is_fromfile = false;
}
if (tb_key.Text == string.Empty)
{
MessageBox.Show("请输入密钥!!", "提示");
return;
}
tb_res_sm4.Clear();
tb_deinfo_sm4.Clear();
string tmp_key = tb_key.Text;
byte[] key_tmp = Encoding.Default.GetBytes(tmp_key);
byte[] digest;
SM3Digest md = new SM3Digest();
md.BlockUpdate(key_tmp, 0, key_tmp.Length);
digest = new byte[md.GetDigestSize()];
md.DoFinal(digest, 0);
string hex = Encoding.UTF8.GetString(Hex.Encode(digest));
string key_temp = hex.Substring(0, 32);
byte[] keybytes = Hex.Decode(key_temp);
byte[] plain = null;
byte[] iv = new byte[16];
byte[] file_bytedata = null;
if (rb_ecb.IsChecked == true)
{
plain = sm4_decrypt(bytedata_de, keybytes, "ECB", null);
}
else if (rb_cbc.IsChecked == true)
{
if (is_fromfile == false)
{
iv = Encoding.UTF8.GetBytes(tb_iv.Text);
plain = sm4_decrypt(bytedata_de, keybytes, "CBC", iv);
}
else
{
Array.Copy(bytedata, iv, 16);
file_bytedata = new byte[bytedata.Length - 16];
Array.Copy(bytedata, 16, file_bytedata, 0, (bytedata.Length - 16));//获取除去初始向量后的密文数据
plain = sm4_decrypt(Hex.Decode(file_bytedata), keybytes, "CBC", iv);
}
}
else if (rb_cfb.IsChecked == true)
{
if (is_fromfile == false)
{
iv = Encoding.UTF8.GetBytes(tb_iv.Text);
plain = sm4_decrypt(bytedata_de, keybytes, "CFB", iv);
}
else
{
Array.Copy(bytedata, iv, 16);
file_bytedata = new byte[bytedata.Length - 16];
Array.Copy(bytedata, 16, file_bytedata, 0, (bytedata.Length - 16));
plain = sm4_decrypt(Hex.Decode(file_bytedata), keybytes, "CFB", iv);
}
}
else if (rb_ofb.IsChecked == true)
{
if (is_fromfile == false)
{
iv = Encoding.UTF8.GetBytes(tb_iv.Text);
plain = sm4_decrypt(bytedata_de, keybytes, "OFB", iv);
}
else
{
Array.Copy(bytedata, iv, 16);
file_bytedata = new byte[bytedata.Length - 16];
Array.Copy(bytedata, 16, file_bytedata, 0, (bytedata.Length - 16));
plain = sm4_decrypt(Hex.Decode(file_bytedata), keybytes, "OFB", iv);
}
}
else if (rb_ctr.IsChecked == true)
{
if (is_fromfile == false)
{
iv = Encoding.UTF8.GetBytes(tb_iv.Text);
plain = sm4_decrypt(bytedata_de, keybytes, "CTR", iv);
}
else
{
Array.Copy(bytedata, iv, 16);
file_bytedata = new byte[bytedata.Length - 16];
Array.Copy(bytedata, 16, file_bytedata, 0, (bytedata.Length - 16));
plain = sm4_decrypt(Hex.Decode(file_bytedata), keybytes, "CTR", iv);
}
}
else
{
MessageBox.Show("请选择解密模式!!", "提示");
return;
}
if (plain != null)
{
string str_plain = Encoding.UTF8.GetString(plain);
tb_res.Clear();
tb_res_sm4.AppendText(str_plain);
if (is_fromfile == true)//输入为文件时
{
string extension = System.IO.Path.GetExtension(tb_filepath_sm4.Text);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "保存解密文件";
sfd.Filter = "All files|*" + extension;
if (sfd.ShowDialog() == true)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
fs.Write(plain, 0, plain.Length);
tb_deinfo_sm4.AppendText(" 解密文件路径:" + sfd.FileName);
fs.Close();
MessageBox.Show("已成功解密文件!!", "提示");
}
else
{
MessageBox.Show("请保存文件!!", "提示");
return;
}
}
else
{
tb_deinfo_sm4.Text = "解密完成,详见运算结果";
}
}
else
{
MessageBox.Show("解密失败!请检查密钥与模式是否正确!!", "提示");
return;
}
}
}
/// <summary>
/// 加密函数
/// </summary>
/// <param name="plain"></param>
/// <param name="user_key"></param>
/// <param name="mode"></param>
/// <returns></returns>
private byte[] sm4_encrypt(byte[] plain, byte[] keyBytes, string mode, byte[] iv)
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
if (mode.Equals("ECB"))
{
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
inCipher.Init(true, key);
byte[] cipher = inCipher.DoFinal(plain);
return cipher;
}
else if (mode.Equals("CBC") && iv != null)
{
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
inCipher.Init(true, keyParamWithIv);
byte[] cipher = inCipher.DoFinal(plain);
return cipher;
}
else if (mode.Equals("CFB") && iv != null)
{
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CFB/PKCS7Padding");
inCipher.Init(true, keyParamWithIv);
byte[] cipher = inCipher.DoFinal(plain);
return cipher;
}
else if (mode.Equals("OFB") && iv != null)
{
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/OFB/PKCS7Padding");
inCipher.Init(true, keyParamWithIv);
byte[] cipher = inCipher.DoFinal(plain);
return cipher;
}
else if (mode.Equals("CTR") && iv != null)
{
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CTR/PKCS7Padding");
inCipher.Init(true, keyParamWithIv);
byte[] cipher = inCipher.DoFinal(plain);
return cipher;
}
else
{
return null;
}
}
/// <summary>
/// 解密函数
/// </summary>
/// <param name="cipher"></param>
/// <param name="keyBytes"></param>
/// <param name="mode"></param>
/// <param name="iv"></param>
/// <returns></returns>
private byte[] sm4_decrypt(byte[] cipher, byte[] keyBytes, string mode, byte[] iv)
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
if (mode.Equals("ECB"))
{
try
{
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
inCipher.Init(false, key);
byte[] plain = inCipher.DoFinal(cipher);
return plain;
}
catch (Exception)
{
return null;
}
}
else if (mode.Equals("CBC") && iv != null)
{
try
{
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
inCipher.Init(false, keyParamWithIv);
byte[] plain = inCipher.DoFinal(cipher);
return plain;
}
catch (Exception)
{
return null;
}
}
else if (mode.Equals("CFB") && iv != null)
{
try
{
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CFB/PKCS7Padding");
inCipher.Init(false, keyParamWithIv);
byte[] plain = inCipher.DoFinal(cipher);
return plain;
}
catch (Exception)
{
return null;
}
}
else if (mode.Equals("OFB") && iv != null)
{