-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathForm1.cs
More file actions
335 lines (300 loc) · 11.7 KB
/
Form1.cs
File metadata and controls
335 lines (300 loc) · 11.7 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
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using System.Numerics;
namespace EasySafeChat
{
public partial class Form1 : Form
{
private const int N_BITS = 4096;
private const int D_BYTES = N_BITS / 8;
private const int Q_BYTES = D_BYTES / 2;
private const int DP_BYTES = Q_BYTES;
private const int DQ_BYTES = Q_BYTES;
private const int INV_Q_BYTES = Q_BYTES;
private static readonly byte[] EXPONENT = new byte[] { 0x01, 0x00, 0x01 }; // 65537
private const bool USE_OAEP = true;
private const int ENC_BLOCK_BYTES = D_BYTES;
private const int HASH_BYTES = 20;
private const int BLOCK_BYTES = ENC_BLOCK_BYTES - 2 * HASH_BYTES - 2;
// 密钥文件格式:base64编码的n或者p
private const string MY_PUBLIC_KEY_PATH = "MyPublicKey.txt";
private const string MY_PRIVATE_KEY_PATH = "MyPrivateKey.txt";
private const string OTHERS_PUBLIC_KEY_PATH = "OthersPublicKey.txt";
public Form1()
{
InitializeComponent();
}
private static RSAParameters GetFullParams(byte[] n, byte[] p)
{
var otherParams = CalcOtherParams(n, p);
return new RSAParameters
{
P = p,
Q = otherParams.Q,
Exponent = EXPONENT,
Modulus = n,
D = otherParams.D,
DP = otherParams.DP,
DQ = otherParams.DQ,
InverseQ = otherParams.InverseQ,
};
}
private static RSAParameters CalcOtherParams(byte[] _n, byte[] _p)
{
var n = BigIntegerFromBigEndian(_n);
var p = BigIntegerFromBigEndian(_p);
var e = BigIntegerFromBigEndian(EXPONENT);
var q = n / p;
var phiN = n - p - q + 1; // OR: (p - 1) * (q - 1);
var d = CoprimesModInverse(e, phiN);
var dp = d % (p - 1);
var dq = d % (q - 1);
var qInv = CoprimesModInverse(q, p);
return new RSAParameters
{
Q = ReversedBytes(q.ToByteArray(), Q_BYTES),
D = ReversedBytes(d.ToByteArray(), D_BYTES),
DP = ReversedBytes(dp.ToByteArray(), DP_BYTES),
DQ = ReversedBytes(dq.ToByteArray(), DQ_BYTES),
InverseQ = ReversedBytes(qInv.ToByteArray(), INV_Q_BYTES)
};
}
private static byte[] ReversedBytes(byte[] data, int len = 0)
{
var reversed = new byte[data.Length];
Array.Copy(data, 0, reversed, 0, data.Length);
if (len > 0) Array.Resize(ref reversed, len);
Array.Reverse(reversed);
return reversed;
}
private static BigInteger BigIntegerFromBigEndian(byte[] bigEndian)
{
var littleEndian = ReversedBytes(bigEndian);
// 最高位是1要补零,否则被识别为负数
if (bigEndian[0] >= 128) littleEndian = littleEndian.Concat(new byte[] { 0 }).ToArray();
return new BigInteger(littleEndian);
}
// Returns modulo inverse of a with
// respect to m using extended Euclid
// Algorithm Assumption: a and m are
// coprimes, i.e., gcd(A, M) = 1
private static BigInteger CoprimesModInverse(BigInteger A, BigInteger M)
{
BigInteger m0 = M;
BigInteger y = 0, x = 1;
if (M == 1) return 0;
while (A > 1)
{
// q is quotient
BigInteger q = A / M;
BigInteger t = M;
// m is remainder now, process
// same as Euclid's algo
M = A % M;
A = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
private RSACryptoServiceProvider GetMyRsa()
{
if (MyPublicKeyRichTextBox.Text.Length > 0)
{
try
{
var rsaParams = GetFullParams(
Convert.FromBase64String(MyPublicKeyRichTextBox.Lines[0].Trim()),
Convert.FromBase64String(File.ReadAllText(MY_PRIVATE_KEY_PATH).Trim())
);
var myRsa = new RSACryptoServiceProvider();
myRsa.ImportParameters(rsaParams);
return myRsa;
}
catch (Exception)
{
MessageBox.Show(
"你的密钥格式错误,请将其修复或清空",
"错误",
MessageBoxButtons.OK, MessageBoxIcon.Error
);
return null;
}
}
else
{
// 如果为空,则生成新密钥
var myRsa = new RSACryptoServiceProvider(N_BITS);
var rsaParams = myRsa.ExportParameters(true);
MyPublicKeyRichTextBox.Lines = new string[] {
Convert.ToBase64String(rsaParams.Modulus),
};
// 立即存入文件
MyPublicKeyTimer_Tick(null, null);
File.WriteAllText(MY_PRIVATE_KEY_PATH, Convert.ToBase64String(rsaParams.P));
return myRsa;
}
}
private RSACryptoServiceProvider GetOthersRsa()
{
if (OthersPublicKeyRichTextBox.Text.Length > 0)
{
try
{
var rsaParams = new RSAParameters
{
Exponent = EXPONENT,
Modulus = Convert.FromBase64String(OthersPublicKeyRichTextBox.Lines[0].Trim())
};
var othersRsa = new RSACryptoServiceProvider();
othersRsa.ImportParameters(rsaParams);
return othersRsa;
}
catch (Exception)
{
MessageBox.Show(
$"对方公钥格式错误,请修复",
"错误",
MessageBoxButtons.OK, MessageBoxIcon.Error
);
}
}
return null;
}
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(MY_PUBLIC_KEY_PATH))
MyPublicKeyRichTextBox.Text = File.ReadAllText(MY_PUBLIC_KEY_PATH);
if (MyPublicKeyRichTextBox.Text.Length == 0) GetMyRsa();
if (File.Exists(OTHERS_PUBLIC_KEY_PATH))
OthersPublicKeyRichTextBox.Text = File.ReadAllText(OTHERS_PUBLIC_KEY_PATH);
if (OthersPublicKeyRichTextBox.Text.Length == 0)
OthersPublicKeyRichTextBox.Text = "请填入对方公钥";
}
private void MyPublicKey_TextChanged(object sender, EventArgs e)
{
MyPublicKeyTimer.Stop();
MyPublicKeyTimer.Start();
}
private void OthersPublicKey_TextChanged(object sender, EventArgs e)
{
OthersPublicKeyTimer.Stop();
OthersPublicKeyTimer.Start();
}
private void MyPublicKeyTimer_Tick(object sender, EventArgs e)
{
File.WriteAllText(MY_PUBLIC_KEY_PATH, MyPublicKeyRichTextBox.Text);
}
private void OthersPublicKeyTimer_Tick(object sender, EventArgs e)
{
File.WriteAllText(OTHERS_PUBLIC_KEY_PATH, OthersPublicKeyRichTextBox.Text);
}
private void SelectCurrentLine(RichTextBox textBox)
{
var start = textBox.GetFirstCharIndexOfCurrentLine();
var lineIndex = textBox.GetLineFromCharIndex(start);
if (lineIndex < textBox.Lines.Length)
{
var end = textBox.Lines[lineIndex].Length;
textBox.Select(start, end);
}
}
private void MyPublicKeyTextBox_DoubleClick(object sender, EventArgs e)
{
SelectCurrentLine(MyPublicKeyRichTextBox);
}
private void OthersPublicKeyTextBox_DoubleClick(object sender, EventArgs e)
{
SelectCurrentLine(OthersPublicKeyRichTextBox);
}
private void MyTextBox_DoubleClick(object sender, EventArgs e)
{
SelectCurrentLine(MyRichTextBox);
}
private void OthersTextBox_DoubleClick(object sender, EventArgs e)
{
SelectCurrentLine(OthersRichTextBox);
}
private void RsaEncrypt(RichTextBox richTextBox, RSACryptoServiceProvider rsa)
{
if (richTextBox.Text.Length == 0 || rsa is null) return;
try
{
var plainBytes = Encoding.UTF8.GetBytes(richTextBox.Text);
// 将plainBytes分块加密、整合
byte[] plainBuffer;
var cipherBytesList = new List<byte>();
for (int i = 0; i < plainBytes.Length; i += BLOCK_BYTES)
{
var len = plainBytes.Length - i < BLOCK_BYTES ? plainBytes.Length - i : BLOCK_BYTES;
plainBuffer = new byte[len];
Array.Copy(plainBytes, i, plainBuffer, 0, len);
cipherBytesList.AddRange(rsa.Encrypt(plainBuffer, USE_OAEP));
}
var cipherBytes = cipherBytesList.ToArray();
var cipherBase64 = Convert.ToBase64String(cipherBytes);
richTextBox.Text = cipherBase64;
}
catch (Exception)
{
MessageBox.Show(
"加密失败!", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error
);
}
}
private void RsaDecrypt(RichTextBox richTextBox, RSACryptoServiceProvider rsa)
{
if (richTextBox.Text.Length == 0 || rsa is null) return;
try
{
var cipherBytes = Convert.FromBase64String(richTextBox.Text);
// 将cipherBytes分块解密、整合
byte[] cipherBuffer;
var plainBytesList = new List<byte>();
for (int i = 0; i < cipherBytes.Length; i += ENC_BLOCK_BYTES)
{
cipherBuffer = new byte[ENC_BLOCK_BYTES];
Array.Copy(cipherBytes, i, cipherBuffer, 0, ENC_BLOCK_BYTES);
plainBytesList.AddRange(rsa.Decrypt(cipherBuffer, USE_OAEP));
}
var plainBytes = plainBytesList.ToArray();
var plainText = Encoding.UTF8.GetString(plainBytes);
richTextBox.Text = plainText;
}
catch (Exception)
{
MessageBox.Show(
"解密失败!", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error
);
}
}
private void MyTextDecryptBtn_Click(object sender, EventArgs e)
{
RsaDecrypt(MyRichTextBox, GetMyRsa());
}
private void MyTextEncryptBtn_Click(object sender, EventArgs e)
{
RsaEncrypt(MyRichTextBox, GetMyRsa());
}
private void OthersTextEncryptBtn_Click(object sender, EventArgs e)
{
RsaEncrypt(OthersRichTextBox, GetOthersRsa());
}
}
}