|
| 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