-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
RSAKeyFormatHelper.cs
310 lines (262 loc) · 10.5 KB
/
RSAKeyFormatHelper.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Formats.Asn1;
using System.Security.Cryptography.Asn1;
namespace System.Security.Cryptography
{
internal static partial class RSAKeyFormatHelper
{
private static readonly string[] s_validOids =
{
Oids.Rsa,
};
internal static void FromPkcs1PrivateKey(
ReadOnlyMemory<byte> keyData,
in AlgorithmIdentifierAsn algId,
out RSAParameters ret)
{
RSAPrivateKeyAsn key = RSAPrivateKeyAsn.Decode(keyData, AsnEncodingRules.BER);
if (!algId.HasNullEquivalentParameters())
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
const int MaxSupportedVersion = 0;
if (key.Version > MaxSupportedVersion)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_RSAPrivateKey_VersionTooNew,
key.Version,
MaxSupportedVersion));
}
// The modulus size determines the encoded output size of the CRT parameters.
byte[] n = key.Modulus.ToByteArray(isUnsigned: true, isBigEndian: true);
int halfModulusLength = (n.Length + 1) / 2;
ret = new RSAParameters
{
Modulus = n,
Exponent = key.PublicExponent.ToByteArray(isUnsigned: true, isBigEndian: true),
D = key.PrivateExponent.ExportKeyParameter(n.Length),
P = key.Prime1.ExportKeyParameter(halfModulusLength),
Q = key.Prime2.ExportKeyParameter(halfModulusLength),
DP = key.Exponent1.ExportKeyParameter(halfModulusLength),
DQ = key.Exponent2.ExportKeyParameter(halfModulusLength),
InverseQ = key.Coefficient.ExportKeyParameter(halfModulusLength),
};
}
internal static void ReadRsaPublicKey(
ReadOnlyMemory<byte> keyData,
in AlgorithmIdentifierAsn algId,
out RSAParameters ret)
{
RSAPublicKeyAsn key = RSAPublicKeyAsn.Decode(keyData, AsnEncodingRules.BER);
ret = new RSAParameters
{
Modulus = key.Modulus.ToByteArray(isUnsigned: true, isBigEndian: true),
Exponent = key.PublicExponent.ToByteArray(isUnsigned: true, isBigEndian: true),
};
}
internal static void ReadRsaPublicKey(
ReadOnlyMemory<byte> keyData,
out int bytesRead)
{
int read;
try
{
AsnValueReader reader = new AsnValueReader(keyData.Span, AsnEncodingRules.DER);
read = reader.PeekEncodedValue().Length;
RSAPublicKeyAsn.Decode(keyData, AsnEncodingRules.BER);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
bytesRead = read;
}
internal static void ReadSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead,
out RSAParameters key)
{
KeyFormatHelper.ReadSubjectPublicKeyInfo<RSAParameters>(
s_validOids,
source,
ReadRsaPublicKey,
out bytesRead,
out key);
}
internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
ReadOnlyMemory<byte> source,
out int bytesRead)
{
return KeyFormatHelper.ReadSubjectPublicKeyInfo(
s_validOids,
source,
out bytesRead);
}
/// <summary>
/// Checks that a SubjectPublicKeyInfo represents an RSA key.
/// </summary>
/// <returns>The number of bytes read from <paramref name="source"/>.</returns>
internal static unsafe int CheckSubjectPublicKeyInfo(ReadOnlySpan<byte> source)
{
int bytesRead;
fixed (byte* ptr = source)
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
_ = ReadSubjectPublicKeyInfo(manager.Memory, out bytesRead);
}
}
return bytesRead;
}
public static void ReadPkcs8(
ReadOnlySpan<byte> source,
out int bytesRead,
out RSAParameters key)
{
KeyFormatHelper.ReadPkcs8<RSAParameters>(
s_validOids,
source,
FromPkcs1PrivateKey,
out bytesRead,
out key);
}
internal static ReadOnlyMemory<byte> ReadPkcs8(
ReadOnlyMemory<byte> source,
out int bytesRead)
{
return KeyFormatHelper.ReadPkcs8(
s_validOids,
source,
out bytesRead);
}
/// <summary>
/// Checks that a Pkcs8PrivateKeyInfo represents an RSA key.
/// </summary>
/// <returns>The number of bytes read from <paramref name="source"/>.</returns>
internal static unsafe int CheckPkcs8(ReadOnlySpan<byte> source)
{
int bytesRead;
fixed (byte* ptr = source)
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
_ = ReadPkcs8(manager.Memory, out bytesRead);
}
}
return bytesRead;
}
internal static AsnWriter WriteSubjectPublicKeyInfo(ReadOnlySpan<byte> pkcs1PublicKey)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.PushSequence();
WriteAlgorithmIdentifier(writer);
writer.WriteBitString(pkcs1PublicKey);
writer.PopSequence();
return writer;
}
internal static AsnWriter WriteSubjectPublicKeyInfo(in RSAParameters rsaParameters)
{
AsnWriter pkcs1PublicKey = WritePkcs1PublicKey(rsaParameters);
byte[] rented = CryptoPool.Rent(pkcs1PublicKey.GetEncodedLength());
if (!pkcs1PublicKey.TryEncode(rented, out int written))
{
Debug.Fail("TryEncode failed with a presized buffer");
throw new CryptographicException();
}
AsnWriter ret = WriteSubjectPublicKeyInfo(rented.AsSpan(0, written));
// Only public key data data
CryptoPool.Return(rented, clearSize: 0);
return ret;
}
internal static AsnWriter WritePkcs8PrivateKey(
ReadOnlySpan<byte> pkcs1PrivateKey,
AsnWriter? copyFrom = null)
{
Debug.Assert(copyFrom == null || pkcs1PrivateKey.IsEmpty);
AsnWriter writer = new AsnWriter(AsnEncodingRules.BER);
using (writer.PushSequence())
{
// Version 0 format (no attributes)
writer.WriteInteger(0);
WriteAlgorithmIdentifier(writer);
if (copyFrom != null)
{
using (writer.PushOctetString())
{
copyFrom.CopyTo(writer);
}
}
else
{
writer.WriteOctetString(pkcs1PrivateKey);
}
}
return writer;
}
internal static AsnWriter WritePkcs8PrivateKey(in RSAParameters rsaParameters)
{
AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey(rsaParameters);
return WritePkcs8PrivateKey(ReadOnlySpan<byte>.Empty, pkcs1PrivateKey);
}
private static void WriteAlgorithmIdentifier(AsnWriter writer)
{
writer.PushSequence();
// https://tools.ietf.org/html/rfc3447#appendix-C
//
// --
// -- When rsaEncryption is used in an AlgorithmIdentifier the
// -- parameters MUST be present and MUST be NULL.
// --
writer.WriteObjectIdentifier(Oids.Rsa);
writer.WriteNull();
writer.PopSequence();
}
internal static AsnWriter WritePkcs1PublicKey(in RSAParameters rsaParameters)
{
if (rsaParameters.Modulus == null || rsaParameters.Exponent == null)
{
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.PushSequence();
writer.WriteKeyParameterInteger(rsaParameters.Modulus);
writer.WriteKeyParameterInteger(rsaParameters.Exponent);
writer.PopSequence();
return writer;
}
internal static AsnWriter WritePkcs1PrivateKey(in RSAParameters rsaParameters)
{
if (rsaParameters.Modulus == null || rsaParameters.Exponent == null)
{
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
if (rsaParameters.D == null ||
rsaParameters.P == null ||
rsaParameters.Q == null ||
rsaParameters.DP == null ||
rsaParameters.DQ == null ||
rsaParameters.InverseQ == null)
{
throw new CryptographicException(SR.Cryptography_NotValidPrivateKey);
}
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.PushSequence();
// Format version 0
writer.WriteInteger(0);
writer.WriteKeyParameterInteger(rsaParameters.Modulus);
writer.WriteKeyParameterInteger(rsaParameters.Exponent);
writer.WriteKeyParameterInteger(rsaParameters.D);
writer.WriteKeyParameterInteger(rsaParameters.P);
writer.WriteKeyParameterInteger(rsaParameters.Q);
writer.WriteKeyParameterInteger(rsaParameters.DP);
writer.WriteKeyParameterInteger(rsaParameters.DQ);
writer.WriteKeyParameterInteger(rsaParameters.InverseQ);
writer.PopSequence();
return writer;
}
}
}