From bf1e9f573b31d4e04298f04f7730b13159ef9362 Mon Sep 17 00:00:00 2001 From: Kevin Jones Date: Mon, 30 Jun 2025 10:53:27 -0400 Subject: [PATCH] Fix MLDsaImplementation on Windows to throw a more clear exception and add a test. --- .../Cryptography/MLDsaImplementation.Windows.cs | 9 ++++++++- .../AlgorithmImplementations/MLDsa/MLDsaTestsBase.cs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs b/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs index 45f5f18c38e688..a77f6d7237b8de 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/MLDsaImplementation.Windows.cs @@ -34,8 +34,15 @@ private MLDsaImplementation( [MemberNotNullWhen(true, nameof(s_algHandle))] internal static partial bool SupportsAny() => s_algHandle is not null; - protected override void SignDataCore(ReadOnlySpan data, ReadOnlySpan context, Span destination) => + protected override void SignDataCore(ReadOnlySpan data, ReadOnlySpan context, Span destination) + { + if (!_hasSecretKey) + { + throw new CryptographicException(SR.Cryptography_MLDsaNoSecretKey); + } + Interop.BCrypt.BCryptSignHashPqcPure(_key, data, context, destination); + } protected override bool VerifyDataCore(ReadOnlySpan data, ReadOnlySpan context, ReadOnlySpan signature) => Interop.BCrypt.BCryptVerifySignaturePqcPure(_key, data, context, signature); diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/MLDsa/MLDsaTestsBase.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/MLDsa/MLDsaTestsBase.cs index 2675718198b45c..5bda6b97133dcd 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/MLDsa/MLDsaTestsBase.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/MLDsa/MLDsaTestsBase.cs @@ -279,6 +279,18 @@ public void ImportPrivateSeed_Export(MLDsaKeyInfo info) AssertExtensions.SequenceEqual(info.PrivateSeed, export(mldsa))); } + [Theory] + [MemberData(nameof(MLDsaTestsData.IetfMLDsaAlgorithms), MemberType = typeof(MLDsaTestsData))] + public void SignData_PublicKeyOnlyThrows(MLDsaKeyInfo info) + { + using MLDsa mldsa = ImportPublicKey(info.Algorithm, info.PublicKey); + byte[] destination = new byte[info.Algorithm.SignatureSizeInBytes]; + CryptographicException ce = + Assert.ThrowsAny(() => mldsa.SignData("hello"u8, destination)); + + Assert.DoesNotContain("unknown", ce.Message, StringComparison.OrdinalIgnoreCase); + } + protected static void ExerciseSuccessfulVerify(MLDsa mldsa, byte[] data, byte[] signature, byte[] context) { ReadOnlySpan buffer = [0, 1, 2, 3];