-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Add CompositeMLDsa CNG (NCrypt) #130053
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PranavSenthilnathan
wants to merge
7
commits into
dotnet:main
Choose a base branch
from
PranavSenthilnathan:cmldsa-ncrypt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add CompositeMLDsa CNG (NCrypt) #130053
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b6b9e66
Add CompositeMLDsa CNG (NCrypt)
PranavSenthilnathan ec19e43
Merge remote-tracking branch 'upstream/main' into cmldsa-ncrypt
PranavSenthilnathan 2b558c6
Address some feedback
PranavSenthilnathan 26707b4
remaining feedback
PranavSenthilnathan a5ae831
Remove experimental from internal members
PranavSenthilnathan e73e7e4
Fix BOM
PranavSenthilnathan 66daff6
Merge branch 'main' into cmldsa-ncrypt
PranavSenthilnathan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
238 changes: 227 additions & 11 deletions
238
src/libraries/Common/src/System/Security/Cryptography/CompositeMLDsaCng.Windows.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,31 +1,247 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Diagnostics; | ||
| using System.Formats.Asn1; | ||
| using System.Runtime.Versioning; | ||
| using System.Security.Cryptography.Asn1; | ||
| using Microsoft.Win32.SafeHandles; | ||
|
|
||
| namespace System.Security.Cryptography | ||
| { | ||
| public sealed partial class CompositeMLDsaCng : CompositeMLDsa | ||
| { | ||
| public partial CngKey GetKey() => | ||
| throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLDsa))); | ||
| internal const string NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_44_ECDSA_P256_SHA256 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_44_ECDSA_P256_SHA256; | ||
| internal const string NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_65_ECDSA_P256_SHA512 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_65_ECDSA_P256_SHA512; | ||
| internal const string NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_65_ECDSA_P384_SHA512 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_65_ECDSA_P384_SHA512; | ||
| internal const string NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_87_ECDSA_P384_SHA512 = PqcBlobHelpers.BCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_87_ECDSA_P384_SHA512; | ||
|
|
||
| [SupportedOSPlatform("windows")] | ||
| private static partial CompositeMLDsaAlgorithm AlgorithmFromHandle(CngKey key, out CngKey duplicateKey) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(key); | ||
| ThrowIfNotSupported(); | ||
|
|
||
| if (key.AlgorithmGroup != CngAlgorithmGroup.CompositeMLDsa) | ||
| { | ||
| throw new ArgumentException(SR.Cryptography_ArgCompositeMLDsaRequiresCompositeMLDsaKey, nameof(key)); | ||
| } | ||
|
|
||
| CompositeMLDsaAlgorithm algorithm = AlgorithmFromHandleImpl(key); | ||
|
|
||
| duplicateKey = key.Duplicate(); | ||
| return algorithm; | ||
| } | ||
|
|
||
| private static CompositeMLDsaAlgorithm AlgorithmFromHandleImpl(CngKey key) | ||
| { | ||
| string? parameterSet = | ||
| #if SYSTEM_SECURITY_CRYPTOGRAPHY | ||
| key.HandleNoDuplicate.GetPropertyAsString(KeyPropertyName.ParameterSetName, CngPropertyOptions.None); | ||
| #else | ||
| key.GetPropertyAsString(KeyPropertyName.ParameterSetName, CngPropertyOptions.None); | ||
| #endif | ||
|
|
||
| return parameterSet switch | ||
| { | ||
| NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_44_ECDSA_P256_SHA256 => CompositeMLDsaAlgorithm.MLDsa44WithECDsaP256, | ||
| NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_65_ECDSA_P256_SHA512 => CompositeMLDsaAlgorithm.MLDsa65WithECDsaP256, | ||
| NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_65_ECDSA_P384_SHA512 => CompositeMLDsaAlgorithm.MLDsa65WithECDsaP384, | ||
| NCRYPT_COMPOSITE_MLDSA_PARAMETER_SET_87_ECDSA_P384_SHA512 => CompositeMLDsaAlgorithm.MLDsa87WithECDsaP384, | ||
| _ => throw DebugFailAndGetException(parameterSet), | ||
| }; | ||
|
|
||
| static Exception DebugFailAndGetException(string? parameterSet) | ||
| { | ||
| Debug.Fail($"Unexpected parameter set {parameterSet}"); | ||
| throw new CryptographicException(); | ||
| } | ||
| } | ||
|
|
||
| public partial CngKey GetKey() | ||
| { | ||
| ThrowIfDisposed(); | ||
|
|
||
| return _key.Duplicate(); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override int SignDataCore(ReadOnlySpan<byte> data, ReadOnlySpan<byte> context, Span<byte> destination) => | ||
| throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLDsa))); | ||
| protected override int SignDataCore(ReadOnlySpan<byte> data, ReadOnlySpan<byte> context, Span<byte> destination) | ||
| { | ||
| int bytesWritten = 0; | ||
|
|
||
| using (SafeNCryptKeyHandle duplicatedHandle = _key.Handle) | ||
| { | ||
| fixed (void* pContext = context) | ||
| { | ||
| Interop.BCrypt.BCRYPT_PQDSA_PADDING_INFO paddingInfo = default; | ||
| paddingInfo.pbCtx = (IntPtr)pContext; | ||
| paddingInfo.cbCtx = context.Length; | ||
|
|
||
| bool result = false; | ||
|
|
||
| unsafe | ||
| { | ||
| result = duplicatedHandle.TrySignHash( | ||
| data, | ||
| destination, | ||
| Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PQDSA_FLAG, | ||
| &paddingInfo, | ||
| out bytesWritten); | ||
| } | ||
|
|
||
| if (!result) | ||
| { | ||
| Debug.Fail("Buffer too small but caller should have already validated the buffer size."); | ||
| throw new CryptographicException(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return bytesWritten; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override int ExportCompositeMLDsaPrivateKeyCore(Span<byte> destination) => | ||
| throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLDsa))); | ||
| protected override bool VerifyDataCore(ReadOnlySpan<byte> data, ReadOnlySpan<byte> context, ReadOnlySpan<byte> signature) | ||
| { | ||
| using (SafeNCryptKeyHandle duplicatedHandle = _key.Handle) | ||
| { | ||
| fixed (void* pContext = context) | ||
| { | ||
| Interop.BCrypt.BCRYPT_PQDSA_PADDING_INFO paddingInfo = default; | ||
| paddingInfo.pbCtx = (IntPtr)pContext; | ||
| paddingInfo.cbCtx = context.Length; | ||
|
|
||
| unsafe | ||
| { | ||
| return duplicatedHandle.VerifyHash( | ||
| data, | ||
| signature, | ||
| Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PQDSA_FLAG, | ||
| &paddingInfo); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override int ExportCompositeMLDsaPublicKeyCore(Span<byte> destination) => | ||
| throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLDsa))); | ||
| ExportKey(CngKeyBlobFormat.PQDsaPublicBlob, Algorithm.MaxPublicKeySizeInBytes, destination); | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override bool TryExportPkcs8PrivateKeyCore(Span<byte> destination, out int bytesWritten) => | ||
| throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLDsa))); | ||
| protected override int ExportCompositeMLDsaPrivateKeyCore(Span<byte> destination) | ||
| { | ||
| if (CngPkcs8.AllowsOnlyEncryptedExport(_key)) | ||
| { | ||
| ArraySegment<byte> pkcs8 = GetRentedPkcs8ForEncryptedOnlyExport(); | ||
|
|
||
| try | ||
| { | ||
| ReadOnlySpan<byte> privateKey = KeyFormatHelper.ReadPkcs8([Algorithm.Oid], pkcs8.AsSpan(), out _); | ||
|
|
||
| if (!privateKey.TryCopyTo(destination)) | ||
| { | ||
| Debug.Fail($"Private key size too large for buffer: {privateKey.Length} / {destination.Length}"); | ||
| throw new CryptographicException(); | ||
| } | ||
|
|
||
| return privateKey.Length; | ||
| } | ||
| finally | ||
| { | ||
| CryptoPool.Return(pkcs8); | ||
| } | ||
| } | ||
|
|
||
| return ExportKey(CngKeyBlobFormat.PQDsaPrivateBlob, Algorithm.MaxPrivateKeySizeInBytes, destination); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override bool VerifyDataCore(ReadOnlySpan<byte> data, ReadOnlySpan<byte> context, ReadOnlySpan<byte> signature) => | ||
| throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(CompositeMLDsa))); | ||
| protected override bool TryExportPkcs8PrivateKeyCore(Span<byte> destination, out int bytesWritten) | ||
| { | ||
| bool encryptedOnlyExport = CngPkcs8.AllowsOnlyEncryptedExport(_key); | ||
|
|
||
| if (encryptedOnlyExport) | ||
|
PranavSenthilnathan marked this conversation as resolved.
|
||
| { | ||
| ArraySegment<byte> pkcs8 = GetRentedPkcs8ForEncryptedOnlyExport(); | ||
|
|
||
| try | ||
| { | ||
| if (destination.Length < pkcs8.Count) | ||
| { | ||
| bytesWritten = 0; | ||
| return false; | ||
| } | ||
|
|
||
| bytesWritten = pkcs8.Count; | ||
| pkcs8.AsSpan().CopyTo(destination); | ||
| return true; | ||
| } | ||
| finally | ||
| { | ||
| CryptoPool.Return(pkcs8); | ||
| } | ||
| } | ||
|
|
||
| // Windows NCrypt does not yet support PKCS#8 export for Composite ML-DSA, so build it from the private key. | ||
| return TryExportPkcs8FromExportedPrivateKey(destination, out bytesWritten); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override void Dispose(bool disposing) | ||
| { | ||
| if (disposing) | ||
| { | ||
| _key.Dispose(); | ||
| _key = null!; | ||
| } | ||
|
|
||
| base.Dispose(disposing); | ||
| } | ||
|
|
||
| private int ExportKey(CngKeyBlobFormat blobFormat, int maxKeySize, Span<byte> destination) | ||
| { | ||
| byte[] blob = _key.Export(blobFormat); | ||
|
|
||
| using (PinAndClear.Track(blob)) | ||
| { | ||
| ReadOnlySpan<byte> keyBytes = PqcBlobHelpers.DecodeCompositeMLDsaBlob(blob, out ReadOnlySpan<char> parameterSet, out string blobType); | ||
|
|
||
| if (!PqcBlobHelpers.TryGetCompositeMLDsaParameterSet(Algorithm, out string? expectedParameterSet)) | ||
| { | ||
| Debug.Fail($"Unknown algorithm {Algorithm.Name}."); | ||
| throw new CryptographicException(); | ||
| } | ||
|
|
||
| if (blobType != blobFormat.Format || | ||
| keyBytes.Length > maxKeySize || | ||
| !parameterSet.SequenceEqual(expectedParameterSet)) | ||
| { | ||
| Debug.Fail( | ||
| $"{nameof(blobType)}: {blobType}, " + | ||
| $"{nameof(parameterSet)}: {parameterSet.ToString()}, " + | ||
| $"{nameof(keyBytes)}.Length: {keyBytes.Length} / {destination.Length}"); | ||
|
|
||
| throw new CryptographicException(); | ||
| } | ||
|
|
||
| keyBytes.CopyTo(destination); | ||
| return keyBytes.Length; | ||
| } | ||
| } | ||
|
|
||
| private ArraySegment<byte> GetRentedPkcs8ForEncryptedOnlyExport() | ||
| { | ||
| const string TemporaryExportPassword = "DotnetExportPhrase"; | ||
| byte[] exported = _key.ExportPkcs8KeyBlob(TemporaryExportPassword, 1); | ||
|
|
||
| using (PinAndClear.Track(exported)) | ||
| { | ||
| return KeyFormatHelper.DecryptPkcs8( | ||
| TemporaryExportPassword, | ||
| exported, | ||
| out _); | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.