Skip to content

Commit 632117e

Browse files
Add managed Composite ML-KEM implementation (#132659)
Managed Composite ML-KEM. This implementation is just for OpenSSL. Windows will have a native implementation added in a future PR. Contributes to #129633 --------- Co-authored-by: Copilot App <[email protected]> Copilot-Session: 02fe9eac-5557-460a-aa50-d6a60a546192 Copilot-Session: 11ffe761-e9d2-47c2-ace0-857272c52b10
1 parent 3174387 commit 632117e

22 files changed

Lines changed: 2604 additions & 45 deletions

‎src/libraries/Common/src/System/Security/Cryptography/CompositeMLKem.cs‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,15 @@ public void Encapsulate(out byte[] ciphertext, out byte[] sharedSecret)
135135
byte[] localCiphertext = new byte[Algorithm.CiphertextSizeInBytes];
136136
byte[] localSharedSecret = new byte[Algorithm.SharedSecretSizeInBytes];
137137

138-
EncapsulateCore(localCiphertext, localSharedSecret);
138+
try
139+
{
140+
EncapsulateCore(localCiphertext, localSharedSecret);
141+
}
142+
catch
143+
{
144+
CryptographicOperations.ZeroMemory(localSharedSecret);
145+
throw;
146+
}
139147

140148
sharedSecret = localSharedSecret;
141149
ciphertext = localCiphertext;
@@ -188,7 +196,15 @@ public void Encapsulate(Span<byte> ciphertext, Span<byte> sharedSecret)
188196

189197
ThrowIfDisposed();
190198

191-
EncapsulateCore(ciphertext, sharedSecret);
199+
try
200+
{
201+
EncapsulateCore(ciphertext, sharedSecret);
202+
}
203+
catch
204+
{
205+
CryptographicOperations.ZeroMemory(sharedSecret);
206+
throw;
207+
}
192208
}
193209

194210
/// <summary>
@@ -243,7 +259,17 @@ public byte[] Decapsulate(byte[] ciphertext)
243259
ThrowIfDisposed();
244260

245261
byte[] sharedSecret = new byte[Algorithm.SharedSecretSizeInBytes];
246-
DecapsulateCore(ciphertext, sharedSecret);
262+
263+
try
264+
{
265+
DecapsulateCore(ciphertext, sharedSecret);
266+
}
267+
catch
268+
{
269+
CryptographicOperations.ZeroMemory(sharedSecret);
270+
throw;
271+
}
272+
247273
return sharedSecret;
248274
}
249275

@@ -286,7 +312,15 @@ public void Decapsulate(ReadOnlySpan<byte> ciphertext, Span<byte> sharedSecret)
286312

287313
ThrowIfDisposed();
288314

289-
DecapsulateCore(ciphertext, sharedSecret);
315+
try
316+
{
317+
DecapsulateCore(ciphertext, sharedSecret);
318+
}
319+
catch
320+
{
321+
CryptographicOperations.ZeroMemory(sharedSecret);
322+
throw;
323+
}
290324
}
291325

292326
/// <summary>
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Diagnostics;
5+
using System.Formats.Asn1;
6+
using System.Security.Cryptography.Asn1;
7+
using Internal.Cryptography;
8+
9+
namespace System.Security.Cryptography
10+
{
11+
internal sealed partial class CompositeMLKemManaged
12+
{
13+
private sealed class ECDiffieHellmanKem : TraditionalKem
14+
#if DESIGNTIMEINTERFACES
15+
#pragma warning disable SA1001 // Commas should be spaced correctly
16+
, ITraditionalKemFactory<ECDiffieHellmanKem, ECDiffieHellmanKemAlgorithm>
17+
#pragma warning restore SA1001 // Commas should be spaced correctly
18+
#endif
19+
{
20+
private readonly ECDiffieHellmanKemAlgorithm _algorithm;
21+
private ECDiffieHellman _ecdh;
22+
23+
private ECDiffieHellmanKem(ECDiffieHellman ecdh, ECDiffieHellmanKemAlgorithm algorithm)
24+
{
25+
_ecdh = ecdh;
26+
_algorithm = algorithm;
27+
}
28+
29+
// While some of our OSes support the brainpool curves, not all do. Supporting them
30+
// only in the managed implementation could make migrating to a native implementation
31+
// that omits them a breaking change. This is a minor concern, but be conservative and
32+
// limit this implementation to the NIST curves until native implementations align.
33+
public static bool IsAlgorithmSupported(ECDiffieHellmanKemAlgorithm algorithm) =>
34+
algorithm.CurveOidValue is Oids.secp256r1 or Oids.secp384r1 or Oids.secp521r1;
35+
36+
public static ECDiffieHellmanKem GenerateKey(ECDiffieHellmanKemAlgorithm algorithm) =>
37+
new ECDiffieHellmanKem(ECDiffieHellman.Create(algorithm.Curve), algorithm);
38+
39+
public static ECDiffieHellmanKem ImportPublicKey(ECDiffieHellmanKemAlgorithm algorithm, ReadOnlySpan<byte> source)
40+
{
41+
int fieldWidth = algorithm.FieldSizeInBytes;
42+
43+
// draft-ietf-lamps-pq-composite-kem-19, 4
44+
// public key MUST be encoded as an uncompressed elliptic curve point as in
45+
// section 2.2 of [RFC5480], including the leading byte 0x04
46+
if (source.Length != 1 + 2 * fieldWidth || source[0] != 0x04)
47+
{
48+
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
49+
}
50+
51+
ECParameters parameters = new()
52+
{
53+
Curve = algorithm.Curve,
54+
Q = new ECPoint
55+
{
56+
X = source.Slice(1, fieldWidth).ToArray(),
57+
Y = source.Slice(1 + fieldWidth, fieldWidth).ToArray(),
58+
},
59+
};
60+
61+
return new ECDiffieHellmanKem(ECDiffieHellman.Create(parameters), algorithm);
62+
}
63+
64+
public static ECDiffieHellmanKem ImportPrivateKey(ECDiffieHellmanKemAlgorithm algorithm, ReadOnlySpan<byte> source)
65+
{
66+
Helpers.ThrowIfAsnInvalidLength(source);
67+
68+
ValueECPrivateKey.Decode(source, AsnEncodingRules.DER, out ValueECPrivateKey ecPrivateKey);
69+
70+
if (ecPrivateKey.Version != 1 ||
71+
ecPrivateKey.HasPublicKey ||
72+
!ecPrivateKey.HasParameters ||
73+
ecPrivateKey.Parameters.Named != algorithm.CurveOidValue ||
74+
ecPrivateKey.PrivateKey.Length != algorithm.OrderSizeInBytes)
75+
{
76+
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
77+
}
78+
79+
byte[] d = new byte[ecPrivateKey.PrivateKey.Length];
80+
81+
using (PinAndClear.Track(d))
82+
{
83+
ecPrivateKey.PrivateKey.CopyTo(d);
84+
85+
ECParameters parameters = new()
86+
{
87+
Curve = algorithm.Curve,
88+
D = d,
89+
};
90+
91+
parameters.Validate();
92+
93+
return new ECDiffieHellmanKem(ECDiffieHellman.Create(parameters), algorithm);
94+
}
95+
}
96+
97+
internal override void Encapsulate(Span<byte> ciphertext, Span<byte> sharedSecret)
98+
{
99+
// draft-ietf-lamps-pq-composite-kem-19, 2.2
100+
// DHKEM.Encaps(pkR):
101+
// (skE, pkE) = GenerateKeyPair()
102+
// ss = DH(skE, pkR)
103+
// ct = SerializePublicKey(pkE)
104+
//
105+
// return ss, ct
106+
107+
using (ECDiffieHellman ephemeral = ECDiffieHellman.Create(_algorithm.Curve))
108+
using (ECDiffieHellmanPublicKey recipientPublicKey = _ecdh.PublicKey)
109+
{
110+
ExportPublicKey(ephemeral, _algorithm, ciphertext);
111+
112+
// The caller clears sharedSecret, even when this method throws, so no cleanup is needed here.
113+
DeriveSecret(ephemeral, recipientPublicKey, sharedSecret);
114+
}
115+
}
116+
117+
internal override void Decapsulate(ReadOnlySpan<byte> ciphertext, Span<byte> sharedSecret)
118+
{
119+
// draft-ietf-lamps-pq-composite-kem-19, 2.2
120+
// DHKEM.Decaps(skR, ct):
121+
// pkE = DeserializePublicKey(ct)
122+
// ss = DH(skR, pkE)
123+
//
124+
// return ss
125+
126+
using (ECDiffieHellmanKem ephemeral = ImportPublicKey(_algorithm, ciphertext))
127+
using (ECDiffieHellmanPublicKey ephemeralPublicKey = ephemeral._ecdh.PublicKey)
128+
{
129+
// The caller clears sharedSecret, even when this method throws, so no cleanup is needed here.
130+
DeriveSecret(_ecdh, ephemeralPublicKey, sharedSecret);
131+
}
132+
}
133+
134+
internal override int ExportPublicKey(Span<byte> destination)
135+
{
136+
ExportPublicKey(_ecdh, _algorithm, destination);
137+
return 1 + 2 * _algorithm.FieldSizeInBytes;
138+
}
139+
140+
internal override int ExportPrivateKey(Span<byte> destination)
141+
{
142+
ECParameters parameters = _ecdh.ExportParameters(includePrivateParameters: true);
143+
144+
Debug.Assert(parameters.D is not null);
145+
146+
using (PinAndClear.Track(parameters.D))
147+
{
148+
if (parameters.D.Length != _algorithm.OrderSizeInBytes ||
149+
!parameters.Curve.IsNamed ||
150+
parameters.Curve.Oid.Value != _algorithm.CurveOidValue)
151+
{
152+
Debug.Fail("ECDH exported unexpected private key parameters.");
153+
throw new CryptographicException();
154+
}
155+
156+
AsnWriter writer = new(AsnEncodingRules.DER);
157+
158+
try
159+
{
160+
ValueECPrivateKey ecPrivateKey = new()
161+
{
162+
Version = 1,
163+
PrivateKey = parameters.D,
164+
Parameters = new ValueECDomainParameters
165+
{
166+
Named = _algorithm.CurveOidValue,
167+
},
168+
};
169+
170+
ecPrivateKey.Encode(writer);
171+
172+
if (!writer.TryEncode(destination, out int bytesWritten))
173+
{
174+
Debug.Fail("The ECDH private key destination was unexpectedly too small.");
175+
throw new CryptographicException();
176+
}
177+
178+
return bytesWritten;
179+
}
180+
finally
181+
{
182+
writer.Reset();
183+
}
184+
}
185+
}
186+
187+
protected override void Dispose(bool disposing)
188+
{
189+
if (disposing)
190+
{
191+
_ecdh?.Dispose();
192+
_ecdh = null!;
193+
}
194+
195+
base.Dispose(disposing);
196+
}
197+
198+
private static void DeriveSecret(ECDiffieHellman ownKey, ECDiffieHellmanPublicKey otherParty, Span<byte> destination)
199+
{
200+
byte[] secret = ownKey.DeriveRawSecretAgreement(otherParty);
201+
202+
try
203+
{
204+
if (secret.Length != destination.Length)
205+
{
206+
Debug.Fail("ECDH produced an unexpected shared secret length.");
207+
throw new CryptographicException();
208+
}
209+
210+
secret.CopyTo(destination);
211+
}
212+
finally
213+
{
214+
CryptographicOperations.ZeroMemory(secret);
215+
}
216+
}
217+
218+
private static void ExportPublicKey(ECDiffieHellman key, ECDiffieHellmanKemAlgorithm algorithm, Span<byte> destination)
219+
{
220+
int fieldWidth = algorithm.FieldSizeInBytes;
221+
Debug.Assert(destination.Length >= 1 + 2 * fieldWidth);
222+
223+
ECParameters parameters = key.ExportParameters(includePrivateParameters: false);
224+
byte[]? x = parameters.Q.X;
225+
byte[]? y = parameters.Q.Y;
226+
227+
if (x is null ||
228+
y is null ||
229+
x.Length != fieldWidth ||
230+
y.Length != fieldWidth ||
231+
!parameters.Curve.IsNamed ||
232+
parameters.Curve.Oid.Value != algorithm.CurveOidValue)
233+
{
234+
Debug.Fail("ECDH exported unexpected public key parameters.");
235+
throw new CryptographicException();
236+
}
237+
238+
destination[0] = 0x04;
239+
x.CopyTo(destination.Slice(1, fieldWidth));
240+
y.CopyTo(destination.Slice(1 + fieldWidth, fieldWidth));
241+
}
242+
}
243+
}
244+
}

0 commit comments

Comments
 (0)