mirrored from https://www.bouncycastle.org/repositories/bc-csharp
-
Notifications
You must be signed in to change notification settings - Fork 602
Expand file tree
/
Copy pathPrivateKeyInfoFactory.cs
More file actions
362 lines (304 loc) · 15.7 KB
/
Copy pathPrivateKeyInfoFactory.cs
File metadata and controls
362 lines (304 loc) · 15.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
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
using System;
using System.Collections.Generic;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.EdEC;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Rosstandart;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Pkcs
{
/// <summary>
/// A factory to produce <see cref="PrivateKeyInfo"/> (PKCS#8) objects from Bouncy Castle private key parameters.
/// </summary>
public static class PrivateKeyInfoFactory
{
private static readonly HashSet<DerObjectIdentifier> cryptoProOids = new HashSet<DerObjectIdentifier>
{
CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
CryptoProObjectIdentifiers.GostR3410x2001CryptoProB,
CryptoProObjectIdentifiers.GostR3410x2001CryptoProC,
CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchA,
CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchB,
};
/// <summary>
/// Create a <see cref="PrivateKeyInfo"/> representation of a private key.
/// </summary>
/// <example>
/// Example of exporting a private key to PKCS#8 bytes:
/// <code>
/// byte[] pkcs8Bytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey).GetEncoded();
/// </code>
/// </example>
/// <param name="privateKey">The private key parameters.</param>
/// <returns>The <see cref="PrivateKeyInfo"/> object.</returns>
public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter privateKey) =>
CreatePrivateKeyInfo(privateKey, null);
/// <summary>
/// Create a <see cref="PrivateKeyInfo"/> representation of a private key with attributes.
/// </summary>
/// <param name="privateKey">The key to be encoded into the info object.</param>
/// <param name="attributes">The set of attributes to be included.</param>
/// <returns>The appropriate <see cref="PrivateKeyInfo"/>.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="privateKey"/> is null.</exception>
/// <exception cref="ArgumentException">If a public key is passed instead of a private key.</exception>
public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter privateKey, Asn1Set attributes)
{
if (privateKey == null)
throw new ArgumentNullException(nameof(privateKey));
if (!privateKey.IsPrivate)
throw new ArgumentException("Public key passed - private key expected", nameof(privateKey));
if (privateKey is ElGamalPrivateKeyParameters elGamalKey)
{
ElGamalParameters egp = elGamalKey.Parameters;
var algParams = new ElGamalParameter(egp.P, egp.G);
var algID = new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm, algParams);
return new PrivateKeyInfo(algID, new DerInteger(elGamalKey.X), attributes);
}
if (privateKey is DsaPrivateKeyParameters dsaKey)
{
DsaParameters dp = dsaKey.Parameters;
var algParams = new DsaParameter(dp.P, dp.Q, dp.G);
var algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, algParams);
return new PrivateKeyInfo(algID, new DerInteger(dsaKey.X), attributes);
}
if (privateKey is DHPrivateKeyParameters dhKey)
{
DHParameters dp = dhKey.Parameters;
var algParams = new DHParameter(dp.P, dp.G, dp.L);
var algID = new AlgorithmIdentifier(dhKey.AlgorithmOid, algParams);
return new PrivateKeyInfo(algID, new DerInteger(dhKey.X), attributes);
}
if (privateKey is RsaKeyParameters rsaKey)
{
var algID = new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
RsaPrivateKeyStructure keyStruct;
if (privateKey is RsaPrivateCrtKeyParameters crtKey)
{
keyStruct = new RsaPrivateKeyStructure(
crtKey.Modulus,
crtKey.PublicExponent,
crtKey.Exponent,
crtKey.P,
crtKey.Q,
crtKey.DP,
crtKey.DQ,
crtKey.QInv);
}
else
{
keyStruct = new RsaPrivateKeyStructure(
rsaKey.Modulus,
BigInteger.Zero,
rsaKey.Exponent,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero);
}
return new PrivateKeyInfo(algID, keyStruct, attributes);
}
if (privateKey is ECPrivateKeyParameters ecKey)
{
var pub = ECKeyPairGenerator.GetCorrespondingPublicKey(ecKey);
var q = pub.Q;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
int encodedLength = q.GetEncodedLength(false);
Span<byte> pubEncoding = encodedLength <= 512
? stackalloc byte[encodedLength]
: new byte[encodedLength];
q.EncodeTo(false, pubEncoding);
#else
byte[] pubEncoding = q.GetEncoded(false);
#endif
DerBitString publicKey = new DerBitString(pubEncoding);
ECDomainParameters dp = ecKey.Parameters;
// ECGOST3410
if (dp is ECGost3410Parameters domainParameters)
{
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
(domainParameters).PublicKeyParamSet,
(domainParameters).DigestParamSet,
(domainParameters).EncryptionParamSet);
int size;
DerObjectIdentifier identifier;
if (cryptoProOids.Contains(gostParams.PublicKeyParamSet))
{
size = 32;
identifier = CryptoProObjectIdentifiers.GostR3410x2001;
}
else
{
bool is512 = ecKey.D.BitLength > 256;
identifier = (is512) ?
RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512 :
RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256;
size = (is512) ? 64 : 32;
}
byte[] encKey = new byte[size];
ExtractBytes(encKey, size, 0, ecKey.D);
return new PrivateKeyInfo(new AlgorithmIdentifier(identifier, gostParams),
new DerOctetString(encKey));
}
int orderBitLength = dp.N.BitLength;
AlgorithmIdentifier algID;
ECPrivateKeyStructure ec;
if (ecKey.AlgorithmName == "ECGOST3410")
{
if (ecKey.PublicKeyParamSet == null)
throw new NotImplementedException("Not a CryptoPro parameter set");
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
ecKey.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gostParams);
// TODO Do we need to pass any parameters here?
ec = new ECPrivateKeyStructure(orderBitLength, ecKey.D, publicKey, null);
}
else
{
X962Parameters x962 = dp.ToX962Parameters();
ec = new ECPrivateKeyStructure(orderBitLength, ecKey.D, publicKey, x962);
algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962);
}
return new PrivateKeyInfo(algID, ec, attributes);
}
if (privateKey is Gost3410PrivateKeyParameters gost3410Key)
{
if (gost3410Key.PublicKeyParamSet == null)
throw new NotImplementedException("Not a CryptoPro parameter set");
// must be little endian
byte[] keyEnc = Arrays.ReverseInPlace(gost3410Key.X.ToByteArrayUnsigned());
Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
gost3410Key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null);
var algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x94, algParams);
return new PrivateKeyInfo(algID, new DerOctetString(keyEnc), attributes);
}
if (privateKey is X448PrivateKeyParameters x448Key)
{
var algID = new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448);
return new PrivateKeyInfo(algID, new DerOctetString(x448Key.GetEncoded()), attributes,
x448Key.GeneratePublicKey().GetEncoded());
}
if (privateKey is X25519PrivateKeyParameters x25519Key)
{
var algID = new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519);
return new PrivateKeyInfo(algID, new DerOctetString(x25519Key.GetEncoded()), attributes,
x25519Key.GeneratePublicKey().GetEncoded());
}
if (privateKey is Ed448PrivateKeyParameters ed448Key)
{
var algID = new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448);
return new PrivateKeyInfo(algID, new DerOctetString(ed448Key.GetEncoded()), attributes,
ed448Key.GeneratePublicKey().GetEncoded());
}
if (privateKey is Ed25519PrivateKeyParameters ed25519Key)
{
var algID = new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519);
return new PrivateKeyInfo(algID, new DerOctetString(ed25519Key.GetEncoded()), attributes,
ed25519Key.GeneratePublicKey().GetEncoded());
}
if (privateKey is MLDsaPrivateKeyParameters mlDsaKey)
{
var algID = new AlgorithmIdentifier(mlDsaKey.Parameters.Oid);
var privateKeyAsn1 = GetMLDsaPrivateKeyAsn1(mlDsaKey);
// NOTE: The public key can be derived from the private key
byte[] publicKey = null;
return new PrivateKeyInfo(algID, privateKeyAsn1, attributes, publicKey);
}
if (privateKey is MLKemPrivateKeyParameters mlKemKey)
{
var algID = new AlgorithmIdentifier(mlKemKey.Parameters.Oid);
var privateKeyAsn1 = GetMLKemPrivateKeyAsn1(mlKemKey);
// NOTE: The private key already includes the public key
byte[] publicKey = null;
return new PrivateKeyInfo(algID, privateKeyAsn1, attributes, publicKey);
}
if (privateKey is SlhDsaPrivateKeyParameters slhDsaKey)
{
var algID = new AlgorithmIdentifier(slhDsaKey.Parameters.Oid);
// NOTE: The private key already includes the public key
DerBitString publicKey = null;
return PrivateKeyInfo.Create(algID, new DerOctetString(slhDsaKey.GetEncoded()), attributes, publicKey);
}
throw new ArgumentException("Class provided is not convertible: " + Platform.GetTypeName(privateKey));
}
/// <summary>
/// Create a <see cref="PrivateKeyInfo"/> from an encrypted representation using a passphrase.
/// </summary>
/// <param name="passPhrase">The password for decryption.</param>
/// <param name="encInfo">The encrypted private key information.</param>
/// <returns>A <see cref="PrivateKeyInfo"/> object.</returns>
public static PrivateKeyInfo CreatePrivateKeyInfo(char[] passPhrase, EncryptedPrivateKeyInfo encInfo) =>
CreatePrivateKeyInfo(passPhrase, false, encInfo);
/// <summary>
/// Create a <see cref="PrivateKeyInfo"/> from an encrypted representation using a passphrase.
/// </summary>
/// <param name="passPhrase">The password for decryption.</param>
/// <param name="wrongPkcs12Zero">If true, uses a specific zero-padding for PKCS#12 PBE (for compatibility).</param>
/// <param name="encInfo">The encrypted private key information.</param>
/// <returns>A <see cref="PrivateKeyInfo"/> object.</returns>
/// <exception cref="ArgumentException">If the encryption algorithm is unknown.</exception>
public static PrivateKeyInfo CreatePrivateKeyInfo(char[] passPhrase, bool wrongPkcs12Zero,
EncryptedPrivateKeyInfo encInfo)
{
AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;
IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;
if (cipher == null)
throw new Exception("Unknown encryption algorithm: " + algID.Algorithm);
ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
algID, passPhrase, wrongPkcs12Zero);
cipher.Init(false, cipherParameters);
byte[] keyBytes = cipher.DoFinal(encInfo.GetEncryptedData());
return PrivateKeyInfo.GetInstance(keyBytes);
}
private static void ExtractBytes(byte[] encKey, int size, int offSet, BigInteger bI)
{
byte[] val = bI.ToByteArray();
if (val.Length < size)
{
byte[] tmp = new byte[size];
Array.Copy(val, 0, tmp, tmp.Length - val.Length, val.Length);
val = tmp;
}
for (int i = 0; i != size; i++)
{
encKey[offSet + i] = val[val.Length - 1 - i];
}
}
private static Asn1Encodable GetMLDsaPrivateKeyAsn1(MLDsaPrivateKeyParameters key)
{
switch (key.PreferredFormat)
{
case MLDsaPrivateKeyParameters.Format.EncodingOnly:
return new DerOctetString(key.GetEncoded());
case MLDsaPrivateKeyParameters.Format.SeedOnly:
return new DerTaggedObject(false, 0, new DerOctetString(key.GetSeed()));
case MLDsaPrivateKeyParameters.Format.SeedAndEncoding:
default:
return new DerSequence(new DerOctetString(key.GetSeed()), new DerOctetString(key.GetEncoded()));
}
}
private static Asn1Encodable GetMLKemPrivateKeyAsn1(MLKemPrivateKeyParameters key)
{
switch (key.PreferredFormat)
{
case MLKemPrivateKeyParameters.Format.EncodingOnly:
return new DerOctetString(key.GetEncoded());
case MLKemPrivateKeyParameters.Format.SeedOnly:
return new DerTaggedObject(false, 0, new DerOctetString(key.GetSeed()));
case MLKemPrivateKeyParameters.Format.SeedAndEncoding:
default:
return new DerSequence(new DerOctetString(key.GetSeed()), new DerOctetString(key.GetEncoded()));
}
}
}
}