forked from myloveCc/NETCore.Encrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRsaProvider.cs
More file actions
342 lines (295 loc) · 10 KB
/
RsaProvider.cs
File metadata and controls
342 lines (295 loc) · 10 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
336
337
338
339
340
341
342
using NETCore.Encrypt.Extensions.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NETCore.Encrypt.Internal
{
/// <summary>
/// RSA provider
///
/// https://github.com/xiangyuecn/RSA-csharp
/// </summary>
internal class RsaProvider
{
static private Regex _PEMCode = new Regex(@"--+.+?--+|\s+");
static private byte[] _SeqOID = new byte[] { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
static private byte[] _Ver = new byte[] { 0x02, 0x01, 0x00 };
/// <summary>
/// Convert pem to rsa,support PKCS#1、PKCS#8
/// </summary>
internal static RSA FromPem(string pem)
{
//var rsaParams = new CspParameters();
//rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
//var rsa = new RSACryptoServiceProvider(rsaParams);
var rsa = RSA.Create();
var param = new RSAParameters();
var base64 = _PEMCode.Replace(pem, "");
var data = Convert.FromBase64String(base64);
if (data == null)
{
throw new Exception("Pem content invalid ");
}
var idx = 0;
//read length
Func<byte, int> readLen = (first) =>
{
if (data[idx] == first)
{
idx++;
if (data[idx] == 0x81)
{
idx++;
return data[idx++];
}
else if (data[idx] == 0x82)
{
idx++;
return (((int)data[idx++]) << 8) + data[idx++];
}
else if (data[idx] < 0x80)
{
return data[idx++];
}
}
throw new Exception("Not found any content in pem file");
};
//read module length
Func<byte[]> readBlock = () =>
{
var len = readLen(0x02);
if (data[idx] == 0x00)
{
idx++;
len--;
}
var val = data.Sub(idx, len);
idx += len;
return val;
};
Func<byte[], bool> eq = (byts) =>
{
for (var i = 0; i < byts.Length; i++, idx++)
{
if (idx >= data.Length)
{
return false;
}
if (byts[i] != data[idx])
{
return false;
}
}
return true;
};
if (pem.Contains("PUBLIC KEY"))
{
/****Use public key****/
readLen(0x30);
if (!eq(_SeqOID))
{
throw new Exception("Unknown pem format");
}
readLen(0x03);
idx++;
readLen(0x30);
//Modulus
param.Modulus = readBlock();
//Exponent
param.Exponent = readBlock();
}
else if (pem.Contains("PRIVATE KEY"))
{
/****Use private key****/
readLen(0x30);
//Read version
if (!eq(_Ver))
{
throw new Exception("Unknown pem version");
}
//Check PKCS8
var idx2 = idx;
if (eq(_SeqOID))
{
//Read one byte
readLen(0x04);
readLen(0x30);
//Read version
if (!eq(_Ver))
{
throw new Exception("Pem version invalid");
}
}
else
{
idx = idx2;
}
//Reda data
param.Modulus = readBlock();
param.Exponent = readBlock();
param.D = readBlock();
param.P = readBlock();
param.Q = readBlock();
param.DP = readBlock();
param.DQ = readBlock();
param.InverseQ = readBlock();
}
else
{
throw new Exception("pem need 'BEGIN' and 'END'");
}
rsa.ImportParameters(param);
return rsa;
}
/// <summary>
/// Converter Rsa to pem ,
/// </summary>
/// <param name="rsa"><see cref="RSACryptoServiceProvider"/></param>
/// <param name="includePrivateParameters">if false only return publick key</param>
/// <param name="isPKCS8">default is false,if true return PKCS#8 pem else return PKCS#1 pem </param>
/// <returns></returns>
internal static string ToPem(RSA rsa, bool includePrivateParameters, bool isPKCS8 = false)
{
var ms = new MemoryStream();
Action<int> writeLenByte = (len) =>
{
if (len < 0x80)
{
ms.WriteByte((byte)len);
}
else if (len <= 0xff)
{
ms.WriteByte(0x81);
ms.WriteByte((byte)len);
}
else
{
ms.WriteByte(0x82);
ms.WriteByte((byte)(len >> 8 & 0xff));
ms.WriteByte((byte)(len & 0xff));
}
};
//write moudle data
Action<byte[]> writeBlock = (byts) =>
{
var addZero = (byts[0] >> 4) >= 0x8;
ms.WriteByte(0x02);
var len = byts.Length + (addZero ? 1 : 0);
writeLenByte(len);
if (addZero)
{
ms.WriteByte(0x00);
}
ms.Write(byts, 0, byts.Length);
};
Func<int, byte[], byte[]> writeLen = (index, byts) =>
{
var len = byts.Length - index;
ms.SetLength(0);
ms.Write(byts, 0, index);
writeLenByte(len);
ms.Write(byts, index, len);
return ms.ToArray();
};
if (!includePrivateParameters)
{
/****Create public key****/
var param = rsa.ExportParameters(false);
ms.WriteByte(0x30);
var index1 = (int)ms.Length;
// Encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
ms.WriteAll(_SeqOID);
//Start with 0x00
ms.WriteByte(0x03);
var index2 = (int)ms.Length;
ms.WriteByte(0x00);
//Content length
ms.WriteByte(0x30);
var index3 = (int)ms.Length;
//Write Modulus
writeBlock(param.Modulus);
//Write Exponent
writeBlock(param.Exponent);
var bytes = ms.ToArray();
bytes = writeLen(index3, bytes);
bytes = writeLen(index2, bytes);
bytes = writeLen(index1, bytes);
return "-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----";
}
else
{
/****Create private key****/
var param = rsa.ExportParameters(true);
//Write total length
ms.WriteByte(0x30);
int index1 = (int)ms.Length;
//Write version
ms.WriteAll(_Ver);
//PKCS8
int index2 = -1, index3 = -1;
if (isPKCS8)
{
ms.WriteAll(_SeqOID);
ms.WriteByte(0x04);
index2 = (int)ms.Length;
ms.WriteByte(0x30);
index3 = (int)ms.Length;
ms.WriteAll(_Ver);
}
//Write data
writeBlock(param.Modulus);
writeBlock(param.Exponent);
writeBlock(param.D);
writeBlock(param.P);
writeBlock(param.Q);
writeBlock(param.DP);
writeBlock(param.DQ);
writeBlock(param.InverseQ);
var bytes = ms.ToArray();
if (index2 != -1)
{
bytes = writeLen(index3, bytes);
bytes = writeLen(index2, bytes);
}
bytes = writeLen(index1, bytes);
var flag = " PRIVATE KEY";
if (!isPKCS8)
{
flag = " RSA" + flag;
}
return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END" + flag + "-----";
}
}
/// <summary>
/// Text break method
/// </summary>
private static string TextBreak(string text, int line)
{
var idx = 0;
var len = text.Length;
var str = new StringBuilder();
while (idx < len)
{
if (idx > 0)
{
str.Append('\n');
}
if (idx + line >= len)
{
str.Append(text.Substring(idx));
}
else
{
str.Append(text.Substring(idx, line));
}
idx += line;
}
return str.ToString();
}
}
}