Skip to content

Commit 6bc923c

Browse files
Add Composite ML-KEM Windows implementation (#132687)
Add BCrypt and NCrypt support for the Windows provider, the approved CNG surface, native blob handling, and Windows provider tests. Contributes to #129633 Fixes #132680 --------- Copilot-Session: 67901feb-14f5-4029-bedd-84864cf3ea53 Copilot-Session: 11ffe761-e9d2-47c2-ace0-857272c52b10
1 parent 939c84a commit 6bc923c

27 files changed

Lines changed: 1376 additions & 22 deletions

‎src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ internal static partial class BCryptNative
2121
internal static class AlgorithmName
2222
{
2323
public const string CompositeMLDsa = "Composite-ML-DSA"; // BCRYPT_COMPOSITE_MLDSA_ALGORITHM
24+
public const string CompositeMLKem = "Composite-ML-KEM"; // BCRYPT_COMPOSITE_MLKEM_ALGORITHM
2425
public const string DSA = "DSA"; // BCRYPT_DSA_ALGORITHM
2526
public const string ECDH = "ECDH"; // BCRYPT_ECDH_ALGORITHM
2627
public const string ECDHP256 = "ECDH_P256"; // BCRYPT_ECDH_P256_ALGORITHM

‎src/libraries/Common/src/Interop/Windows/BCrypt/Interop.Blobs.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ internal enum KeyBlobMagicNumber : int
119119
BCRYPT_COMPOSITE_MLDSA_PUBLIC_MAGIC = 0x4B504D43,
120120
BCRYPT_COMPOSITE_MLDSA_PRIVATE_MAGIC = 0x4B534D43,
121121

122+
BCRYPT_COMPOSITE_MLKEM_PUBLIC_MAGIC = 0x504B4D43, // CMKP
123+
BCRYPT_COMPOSITE_MLKEM_PRIVATE_MAGIC = 0x524B4D43, // CMKR
124+
BCRYPT_COMPOSITE_MLKEM_PRIVATE_IRTF_SEED_MAGIC = 0x534B4D43, // CMKS
125+
122126
BCRYPT_MLDSA_PUBLIC_MAGIC = 0x4B505344,
123127
BCRYPT_MLDSA_PRIVATE_MAGIC = 0x4B535344,
124128
BCRYPT_MLDSA_PRIVATE_SEED_MAGIC = 0x53535344,
@@ -162,6 +166,10 @@ internal static class KeyBlobType
162166
internal const string BCRYPT_MLKEM_PRIVATE_SEED_BLOB = "MLKEMPRIVATESEEDBLOB";
163167
internal const string BCRYPT_MLKEM_PRIVATE_BLOB = "MLKEMPRIVATEBLOB";
164168
internal const string BCRYPT_MLKEM_PUBLIC_BLOB = "MLKEMPUBLICBLOB";
169+
170+
internal const string BCRYPT_COMPOSITE_MLKEM_PUBLIC_BLOB = "COMPMLKEMPUBLICBLOB";
171+
internal const string BCRYPT_COMPOSITE_MLKEM_PRIVATE_BLOB = "COMPMLKEMPRIVATELAMPSBLOB";
172+
internal const string BCRYPT_COMPOSITE_MLKEM_PRIVATE_IRTF_SEED_BLOB = "COMPMLKEMPRIVATEIRTFSEEDBLOB";
165173
}
166174

167175
/// <summary>
@@ -298,6 +306,18 @@ internal struct BCRYPT_MLKEM_KEY_BLOB
298306
internal KeyBlobMagicNumber dwMagic;
299307
internal uint cbParameterSet;
300308
internal uint cbKey;
309+
// WCHAR parameterSet[cbParameterSet / sizeof(WCHAR)]; // Including \0-terminated
310+
// BYTE key[cbKey]; // Key material
311+
}
312+
313+
[StructLayout(LayoutKind.Sequential)]
314+
internal struct BCRYPT_COMPOSITE_MLKEM_KEY_BLOB
315+
{
316+
internal KeyBlobMagicNumber dwMagic;
317+
internal uint cbParameterSet; // Byte size of parameterSet[]
318+
internal uint cbKey; // Byte size of key[]
319+
// WCHAR parameterSet[cbParameterSet / sizeof(WCHAR)]; // Including \0-terminated
320+
// BYTE key[cbKey]; // Key material
301321
}
302322

303323
/// <summary>
Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
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 Microsoft.Win32.SafeHandles;
6+
7+
namespace System.Security.Cryptography
8+
{
9+
public sealed partial class CompositeMLKemCng : CompositeMLKem
10+
{
11+
private const string NCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_768_P256 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_768_P256;
12+
private const string NCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_768_X25519 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_768_X25519;
13+
private const string NCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_1024_P384 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_1024_P384;
14+
15+
private static partial CompositeMLKemAlgorithm AlgorithmFromHandle(CngKey key, out CngKey duplicateKey)
16+
{
17+
ArgumentNullException.ThrowIfNull(key);
18+
19+
if (!CompositeMLKemImplementation.IsSupported)
20+
{
21+
throw new PlatformNotSupportedException(
22+
SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLKem)));
23+
}
24+
25+
if (key.AlgorithmGroup != CngAlgorithmGroup.CompositeMLKem)
26+
{
27+
throw new ArgumentException(SR.Cryptography_ArgCompositeMLKemRequiresCompositeMLKemKey, nameof(key));
28+
}
29+
30+
CompositeMLKemAlgorithm algorithm = AlgorithmFromHandleImpl(key);
31+
duplicateKey = key.Duplicate();
32+
return algorithm;
33+
}
34+
35+
private static CompositeMLKemAlgorithm AlgorithmFromHandleImpl(CngKey key)
36+
{
37+
string? parameterSet =
38+
#if SYSTEM_SECURITY_CRYPTOGRAPHY
39+
key.HandleNoDuplicate.GetPropertyAsString(KeyPropertyName.ParameterSetName, CngPropertyOptions.None);
40+
#else
41+
key.GetPropertyAsString(KeyPropertyName.ParameterSetName, CngPropertyOptions.None);
42+
#endif
43+
44+
return parameterSet switch
45+
{
46+
NCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_768_P256 => CompositeMLKemAlgorithm.MLKem768WithECDiffieHellmanP256,
47+
NCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_768_X25519 => CompositeMLKemAlgorithm.MLKem768WithX25519,
48+
NCRYPT_COMPOSITE_MLKEM_PARAMETER_SET_1024_P384 => CompositeMLKemAlgorithm.MLKem1024WithECDiffieHellmanP384,
49+
_ => throw Fail(parameterSet),
50+
};
51+
52+
static CryptographicException Fail(string? parameterSet)
53+
{
54+
Debug.Fail($"Unexpected Composite ML-KEM parameter set '{parameterSet}'.");
55+
return new CryptographicException();
56+
}
57+
}
58+
59+
public partial CngKey GetKey()
60+
{
61+
ThrowIfDisposed();
62+
63+
return _key.Duplicate();
64+
}
65+
66+
/// <inheritdoc/>
67+
protected override void DecapsulateCore(ReadOnlySpan<byte> ciphertext, Span<byte> sharedSecret)
68+
{
69+
Debug.Assert(IsAlgorithmSupported(Algorithm));
70+
Debug.Assert(ciphertext.Length == Algorithm.CiphertextSizeInBytes);
71+
Debug.Assert(sharedSecret.Length == Algorithm.SharedSecretSizeInBytes);
72+
73+
using (SafeNCryptKeyHandle duplicatedHandle = _key.Handle)
74+
{
75+
uint written = Interop.NCrypt.NCryptDecapsulate(duplicatedHandle, ciphertext, sharedSecret, 0);
76+
77+
if (written != (uint)sharedSecret.Length)
78+
{
79+
Debug.Fail($"Unexpected number of bytes written by NCryptDecapsulate: {written}.");
80+
throw new CryptographicException();
81+
}
82+
}
83+
}
84+
85+
/// <inheritdoc/>
86+
protected override void EncapsulateCore(Span<byte> ciphertext, Span<byte> sharedSecret)
87+
{
88+
Debug.Assert(IsAlgorithmSupported(Algorithm));
89+
Debug.Assert(ciphertext.Length == Algorithm.CiphertextSizeInBytes);
90+
Debug.Assert(sharedSecret.Length == Algorithm.SharedSecretSizeInBytes);
91+
92+
using (SafeNCryptKeyHandle duplicatedHandle = _key.Handle)
93+
{
94+
Interop.NCrypt.NCryptEncapsulate(
95+
duplicatedHandle,
96+
sharedSecret,
97+
ciphertext,
98+
out uint sharedSecretWritten,
99+
out uint ciphertextWritten,
100+
0);
101+
102+
if (sharedSecretWritten != (uint)sharedSecret.Length ||
103+
ciphertextWritten != (uint)ciphertext.Length)
104+
{
105+
Debug.Fail($"Unexpected number of bytes written by NCryptEncapsulate: {sharedSecretWritten} shared secret bytes, {ciphertextWritten} ciphertext bytes.");
106+
throw new CryptographicException();
107+
}
108+
}
109+
}
110+
111+
/// <inheritdoc/>
112+
protected override int ExportEncapsulationKeyCore(Span<byte> destination)
113+
{
114+
Debug.Assert(IsAlgorithmSupported(Algorithm));
115+
Debug.Assert(destination.Length == Algorithm.MaxEncapsulationKeySizeInBytes);
116+
117+
return ExportKey(CngKeyBlobFormat.CompositeMLKemPublicBlob, destination);
118+
}
119+
120+
/// <inheritdoc/>
121+
protected override int ExportDecapsulationKeyCore(Span<byte> destination)
122+
{
123+
Debug.Assert(IsAlgorithmSupported(Algorithm));
124+
Debug.Assert(destination.Length == Algorithm.MaxDecapsulationKeySizeInBytes);
125+
126+
if (CngPkcs8.AllowsOnlyEncryptedExport(_key))
127+
{
128+
ArraySegment<byte> pkcs8 = GetRentedPkcs8ForEncryptedOnlyExport();
129+
130+
try
131+
{
132+
ReadOnlySpan<byte> key = KeyFormatHelper.ReadPkcs8([Algorithm.Oid], pkcs8.AsSpan(), out _);
133+
134+
if (!key.TryCopyTo(destination))
135+
{
136+
Debug.Fail($"Decapsulation key size too large for buffer: {key.Length} / {destination.Length}");
137+
throw new CryptographicException();
138+
}
139+
140+
return key.Length;
141+
}
142+
finally
143+
{
144+
CryptoPool.Return(pkcs8);
145+
}
146+
}
147+
148+
return ExportKey(CngKeyBlobFormat.CompositeMLKemPrivateBlob, destination);
149+
}
150+
151+
/// <inheritdoc/>
152+
protected override bool TryExportPkcs8PrivateKeyCore(Span<byte> destination, out int bytesWritten)
153+
{
154+
Debug.Assert(IsAlgorithmSupported(Algorithm));
155+
156+
if (CngPkcs8.AllowsOnlyEncryptedExport(_key))
157+
{
158+
ArraySegment<byte> pkcs8 = GetRentedPkcs8ForEncryptedOnlyExport();
159+
160+
try
161+
{
162+
if (destination.Length < pkcs8.Count)
163+
{
164+
bytesWritten = 0;
165+
return false;
166+
}
167+
168+
bytesWritten = pkcs8.Count;
169+
pkcs8.AsSpan().CopyTo(destination);
170+
return true;
171+
}
172+
finally
173+
{
174+
CryptoPool.Return(pkcs8);
175+
}
176+
}
177+
178+
// Windows NCrypt does not yet support PKCS#8 export for Composite ML-KEM, so build it from the private key.
179+
return TryExportPkcs8FromExportedDecapsulationKey(destination, out bytesWritten);
180+
}
181+
182+
/// <inheritdoc/>
183+
protected override void Dispose(bool disposing)
184+
{
185+
if (disposing)
186+
{
187+
_key.Dispose();
188+
_key = null!;
189+
}
190+
191+
base.Dispose(disposing);
192+
}
193+
194+
private int ExportKey(CngKeyBlobFormat blobFormat, Span<byte> destination)
195+
{
196+
byte[] blob = _key.Export(blobFormat);
197+
198+
using (PinAndClear.Track(blob))
199+
{
200+
ReadOnlySpan<byte> keyBytes = PqcBlobHelpers.DecodeCompositeMLKemBlob(
201+
blob,
202+
out ReadOnlySpan<char> parameterSet,
203+
out string blobType);
204+
205+
if (!PqcBlobHelpers.TryGetCompositeMLKemParameterSet(Algorithm, out string? expectedParameterSet))
206+
{
207+
Debug.Fail($"Unknown algorithm {Algorithm.Name}.");
208+
throw new CryptographicException();
209+
}
210+
211+
if (blobType != blobFormat.Format ||
212+
keyBytes.Length > destination.Length ||
213+
!parameterSet.SequenceEqual(expectedParameterSet))
214+
{
215+
Debug.Fail(
216+
$"{nameof(blobType)}: {blobType}, " +
217+
$"{nameof(parameterSet)}: {parameterSet.ToString()}, " +
218+
$"{nameof(keyBytes)}.Length: {keyBytes.Length} / {destination.Length}");
219+
220+
throw new CryptographicException();
221+
}
222+
223+
keyBytes.CopyTo(destination);
224+
return keyBytes.Length;
225+
}
226+
}
227+
228+
private ArraySegment<byte> GetRentedPkcs8ForEncryptedOnlyExport()
229+
{
230+
const string TemporaryExportPassword = "DotnetExportPhrase";
231+
byte[] exported = _key.ExportPkcs8KeyBlob(TemporaryExportPassword, 1);
232+
233+
using (PinAndClear.Track(exported))
234+
{
235+
return KeyFormatHelper.DecryptPkcs8(
236+
TemporaryExportPassword,
237+
exported,
238+
out _);
239+
}
240+
}
241+
}
242+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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.CodeAnalysis;
5+
using System.Runtime.Versioning;
6+
using Internal.Cryptography;
7+
8+
namespace System.Security.Cryptography
9+
{
10+
/// <summary>
11+
/// Provides a Cryptography Next Generation (CNG) implementation of the Composite Module-Lattice-Based Key-Encapsulation
12+
/// Mechanism (Composite ML-KEM) algorithm.
13+
/// </summary>
14+
/// <remarks>
15+
/// Developers are encouraged to program against the <see cref="CompositeMLKem" /> base class,
16+
/// rather than any specific derived class. The derived classes are intended for interop with the underlying
17+
/// system cryptographic libraries.
18+
/// </remarks>
19+
[Experimental(Experimentals.PostQuantumCryptographyDiagId, UrlFormat = Experimentals.SharedUrlFormat)]
20+
public sealed partial class CompositeMLKemCng : CompositeMLKem
21+
{
22+
private CngKey _key;
23+
24+
/// <summary>
25+
/// Initializes a new instance of the <see cref="CompositeMLKemCng"/> class by using the specified
26+
/// <see cref="CngKey"/>.
27+
/// </summary>
28+
/// <param name="key">
29+
/// The key that will be used as input to the cryptographic operations performed by the current object.
30+
/// </param>
31+
/// <exception cref="ArgumentNullException">
32+
/// <paramref name="key"/> is <see langword="null"/>.
33+
/// </exception>
34+
/// <exception cref="ArgumentException">
35+
/// <paramref name="key"/> does not specify a Composite ML-KEM algorithm group.
36+
/// </exception>
37+
/// <exception cref="PlatformNotSupportedException">
38+
/// Cryptography Next Generation (CNG) classes are not supported on this system.
39+
/// </exception>
40+
[SupportedOSPlatform("windows")]
41+
public CompositeMLKemCng(CngKey key)
42+
: base(AlgorithmFromHandleWithPlatformCheck(key, out CngKey duplicateKey))
43+
{
44+
_key = duplicateKey;
45+
}
46+
47+
private static CompositeMLKemAlgorithm AlgorithmFromHandleWithPlatformCheck(
48+
CngKey key,
49+
out CngKey duplicateKey)
50+
{
51+
if (!Helpers.IsOSPlatformWindows)
52+
{
53+
throw new PlatformNotSupportedException();
54+
}
55+
56+
return AlgorithmFromHandle(key, out duplicateKey);
57+
}
58+
59+
private static partial CompositeMLKemAlgorithm AlgorithmFromHandle(CngKey key, out CngKey duplicateKey);
60+
61+
/// <summary>
62+
/// Gets a new <see cref="CngKey" /> representing the key used by the current instance.
63+
/// </summary>
64+
/// <exception cref="ObjectDisposedException">
65+
/// This instance has been disposed.
66+
/// </exception>
67+
/// <remarks>
68+
/// This <see cref="CngKey"/> object is not the same as the one passed to <see cref="CompositeMLKemCng(CngKey)"/>,
69+
/// if that constructor was used. However, it will point to the same CNG key.
70+
/// </remarks>
71+
public partial CngKey GetKey();
72+
}
73+
}

0 commit comments

Comments
 (0)