|
| 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 | +} |
0 commit comments