public static void TestNamedImportValidationNegative() { unchecked { using (ECDsa ec = ECDsaFactory.Create()) { ECParameters p = EccTestData.GetNistP224KeyTestData(); Assert.True(p.Curve.IsNamed); var q = p.Q; var c = p.Curve; ec.ImportParameters(p); ECParameters temp = p; temp.Q.X = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = (byte[])p.Q.X.Clone(); temp.Q.X[0]--; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Q.Y = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = (byte[])p.Q.Y.Clone(); temp.Q.Y[0]--; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve = ECCurve.CreateFromOid(new Oid("Invalid", "Invalid")); Assert.ThrowsAny <PlatformNotSupportedException>(() => ec.ImportParameters(temp)); } } }
public MessageClientIdentity(string systemName, string clientName, ECDiffieHellmanCurve curve) { ECDiffieHellman dh; var dhCurve = curve switch { ECDiffieHellmanCurve.P256 => ECCurve.NamedCurves.nistP256, ECDiffieHellmanCurve.P384 => ECCurve.NamedCurves.nistP384, ECDiffieHellmanCurve.P521 => ECCurve.NamedCurves.nistP521, _ => throw new ArgumentOutOfRangeException(nameof(curve)) }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { dh = new ECDiffieHellmanCng(dhCurve); ECDsa = new ECDsaCng(); } else { #if (!NET48) dh = new ECDiffieHellmanOpenSsl(); #else throw new NotSupportedException("ECDiffieHellmanOpenSsl is not supported in .NET 4.8"); #endif ECDsa = new ECDsaOpenSsl(); } SystemName = systemName; Name = clientName; ECDiffieHellman = dh; ECDsa.ImportParameters(dh.ExportExplicitParameters(true)); }
private void UseAfterDispose(ECDsa ecdsa) { byte[] data = { 1 }; byte[] sig; // Ensure the key is populated, then dispose it. using (ecdsa) { sig = SignData(ecdsa, data, HashAlgorithmName.SHA256); } ecdsa.Dispose(); UseAfterDispose(ecdsa, data, sig); if (!(PlatformDetection.IsNetFramework && ecdsa.GetType().Name.EndsWith("Cng"))) { Assert.Throws <ObjectDisposedException>(() => ecdsa.GenerateKey(ECCurve.NamedCurves.nistP256)); Assert.Throws <ObjectDisposedException>( () => ecdsa.ImportParameters(EccTestData.GetNistP256ReferenceKey())); } // Either set_KeySize or SignData should throw. Assert.Throws <ObjectDisposedException>( () => { ecdsa.KeySize = 384; SignData(ecdsa, data, HashAlgorithmName.SHA256); }); }
public static void ExportIncludingPrivateOnPublicOnlyKey() { ECParameters iutParameters = new ECParameters { Curve = ECCurve.NamedCurves.nistP521, Q = { X = "00d45615ed5d37fde699610a62cd43ba76bedd8f85ed31005fe00d6450fbbd101291abd96d4945a8b57bc73b3fe9f4671105309ec9b6879d0551d930dac8ba45d255".HexToByteArray(), Y = "01425332844e592b440c0027972ad1526431c06732df19cd46a242172d4dd67c2c8c99dfc22e49949a56cf90c6473635ce82f25b33682fb19bc33bd910ed8ce3a7fa".HexToByteArray(), }, D = "00816f19c1fb10ef94d4a1d81c156ec3d1de08b66761f03f06ee4bb9dcebbbfe1eaa1ed49a6a990838d8ed318c14d74cc872f95d05d07ad50f621ceb620cd905cfb8".HexToByteArray(), }; using (ECDsa iut = ECDsaFactory.Create()) using (ECDsa cavs = ECDsaFactory.Create()) { iut.ImportParameters(iutParameters); cavs.ImportParameters(iut.ExportParameters(false)); Assert.ThrowsAny <CryptographicException>(() => cavs.ExportParameters(true)); if (ECExplicitCurvesSupported) { Assert.ThrowsAny <CryptographicException>(() => cavs.ExportExplicitParameters(true)); } } }
/// <summary> /// Creates an instance of the platform specific implementation of the cref="ECDsa" algorithm. /// </summary> /// <param name="parameters"> /// The <see cref="ECParameters"/> representing the elliptic curve parameters. /// </param> public static partial ECDsa Create(ECParameters parameters) { ECDsa ecdsa = Create(); ecdsa.ImportParameters(parameters); return(ecdsa); }
public static void AddSigner_ECDSA_EphemeralKey() { using (ECDsa ecdsa = ECDsa.Create()) using (X509Certificate2 publicCertificate = Certificates.ECDsaP256Win.GetCertificate()) using (X509Certificate2 certificateWithKey = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey(exportable: true)) { if (certificateWithKey == null) { return; } using (ECDsa privateKey = certificateWithKey.GetECDsaPrivateKey()) using (ECDsa exportableKey = privateKey.MakeExportable()) { ecdsa.ImportParameters(exportableKey.ExportParameters(true)); } using (X509Certificate2 certWithEphemeralKey = publicCertificate.CopyWithPrivateKey(ecdsa)) { ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3 }); SignedCms cms = new SignedCms(content, false); CmsSigner signer = new CmsSigner(certWithEphemeralKey); cms.ComputeSignature(signer); } } }
public void TestPositive256WithExplicitParameters() { using (ECDsa ecdsa = ECDsaFactory.Create()) { ecdsa.ImportParameters(ECDsaTestData.GetNistP256ExplicitTestData()); Verify256(ecdsa, true); } }
public static void TestExplicitImportValidationNegative() { unchecked { using (ECDsa ec = ECDsaFactory.Create()) { ECParameters p = EccTestData.GetNistP256ExplicitTestData(); Assert.True(p.Curve.IsPrime); ec.ImportParameters(p); ECParameters temp = p; temp.Q.X = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.X = (byte[])p.Q.X.Clone(); --temp.Q.X[0]; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Q.Y = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Q.Y = (byte[])p.Q.Y.Clone(); --temp.Q.Y[0]; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.A = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.A = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.A = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.A = (byte[])p.Curve.A.Clone(); --temp.Curve.A[0]; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.B = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.B = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.B = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.B = (byte[])p.Curve.B.Clone(); --temp.Curve.B[0]; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.Order = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Order = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp = p; temp.Curve.Prime = null; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Prime = new byte[] { }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Prime = new byte[1] { 0x10 }; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); temp.Curve.Prime = (byte[])p.Curve.Prime.Clone(); --temp.Curve.Prime[0]; Assert.ThrowsAny <CryptographicException>(() => ec.ImportParameters(temp)); } } }
public static void TestNamedCurveWithExplicitKey() { using (ECDsa ec = ECDsaFactory.Create()) { ECParameters parameters = EccTestData.GetNistP224KeyTestData(); ec.ImportParameters(parameters); VerifyNamedCurve(parameters, ec, 224, true); } }
private ECDsa Convert(bool includePrivateParameters, bool throwIfNotSupported) { if (!CurveName.HasValue) { if (throwIfNotSupported) { throw new InvalidOperationException("missing required curve name"); } return(null); } KeyCurveName curveName = CurveName.Value; int requiredParameterSize = curveName.KeyParameterSize; if (requiredParameterSize <= 0) { if (throwIfNotSupported) { throw new InvalidOperationException($"invalid curve name: {CurveName.ToString()}"); } return(null); } ECParameters ecParameters = new ECParameters { Curve = ECCurve.CreateFromOid(curveName.Oid), Q = new ECPoint { X = ForceBufferLength(nameof(X), X, requiredParameterSize), Y = ForceBufferLength(nameof(Y), Y, requiredParameterSize), }, }; if (includePrivateParameters && HasPrivateKey) { ecParameters.D = ForceBufferLength(nameof(D), D, requiredParameterSize); } ECDsa ecdsa = ECDsa.Create(); try { ecdsa.ImportParameters(ecParameters); } catch when(!throwIfNotSupported) { ecdsa.Dispose(); return(null); } return(ecdsa); }
public void PublicKey_CannotSign() { using (ECDsa ecdsaPriv = ECDsaFactory.Create()) using (ECDsa ecdsa = ECDsaFactory.Create()) { ECParameters keyParameters = ecdsaPriv.ExportParameters(false); ecdsa.ImportParameters(keyParameters); Assert.ThrowsAny <CryptographicException>( () => ecdsa.SignData(new byte[] { 1, 2, 3, 4, 5 }, HashAlgorithmName.SHA256)); } }
public void FromECDsaNoPrivateKey() { #if NET461 Assert.Ignore("Creating ECDsa with JsonWebKey is not supported on net461."); #else using ECDsa ecdsa = ECDsa.Create(); ECParameters ecParameters = ecdsa.ExportParameters(false); ecdsa.ImportParameters(ecParameters); Assert.That <JsonWebKey>(() => new JsonWebKey(ecdsa, includePrivateParameters: true), Throws.InstanceOf <CryptographicException>()); #endif }
public static void TestGeneralExportWithExplicitParameters() { using (ECDsa ecdsa = ECDsaFactory.Create()) { ECParameters param = EccTestData.GetNistP256ExplicitTestData(); param.Validate(); ecdsa.ImportParameters(param); Assert.True(param.Curve.IsExplicit); param = ecdsa.ExportParameters(false); param.Validate(); // We should have explicit values, not named, as this curve has no name. Assert.True(param.Curve.IsExplicit); } }
/// <summary> /// Creates an instance of the platform specific implementation of the cref="ECDsa" algorithm. /// </summary> /// <param name="parameters"> /// The <see cref="ECParameters"/> representing the elliptic curve parameters. /// </param> public static partial ECDsa Create(ECParameters parameters) { ECDsa ecdsa = Create(); try { ecdsa.ImportParameters(parameters); } catch { ecdsa.Dispose(); throw; } return(ecdsa); }
public static void TestExplicitCurves(CurveDef curveDef) { using (ECDsa ec1 = ECDsaFactory.Create(curveDef.Curve)) { ECParameters param1 = ec1.ExportExplicitParameters(curveDef.IncludePrivate); VerifyExplicitCurve(param1, ec1, curveDef); using (ECDsa ec2 = ECDsaFactory.Create()) { ec2.ImportParameters(param1); ECParameters param2 = ec2.ExportExplicitParameters(curveDef.IncludePrivate); VerifyExplicitCurve(param1, ec1, curveDef); AssertEqual(param1, param2); } } }
internal MessageClientIdentity(string systemName, string clientName, ECDiffieHellman dh, bool isPrivateIdentity) { SystemName = systemName; Name = clientName; ECDiffieHellman = dh; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ECDsa = new ECDsaCng(); } else { ECDsa = new ECDsaOpenSsl(); } ECDsa.ImportParameters(dh.ExportExplicitParameters(isPrivateIdentity)); }
public void SignReturnsNullWithoutPrivateKey() { using ECDsa ecdsa = ECDsa.Create(); ECParameters ecParameters = ecdsa.ExportParameters(false); ecdsa.ImportParameters(ecParameters); JsonWebKey jwk = new JsonWebKey(ecdsa) { Id = "test", }; EcCryptographyProvider client = new EcCryptographyProvider(jwk, null); SignatureAlgorithm algorithm = GetSignatureAlgorithm(jwk); Assert.IsNull(client.Sign(algorithm, new byte[] { 0xff }, default)); }
public static void TestExplicitCurvesSignVerify(CurveDef curveDef) { using (ECDsa ec1 = ECDsaFactory.Create(curveDef.Curve)) { byte[] data = new byte[0x10]; byte[] sig1 = ec1.SignData(data, 0, data.Length, HashAlgorithmName.SHA1); bool verified; verified = ec1.VerifyData(data, sig1, HashAlgorithmName.SHA1); Assert.True(verified); using (ECDsa ec2 = ECDsaFactory.Create()) { ec2.ImportParameters(ec1.ExportExplicitParameters(true)); Assert.Equal(ec1.KeySize, ec2.KeySize); byte[] sig2 = ec2.SignData(data, 0, data.Length, HashAlgorithmName.SHA1); verified = ec2.VerifyData(data, sig2, HashAlgorithmName.SHA1); Assert.True(verified); // Verify key is compatible other signature verified = ec2.VerifyData(data, sig1, HashAlgorithmName.SHA1); Assert.True(verified); verified = ec1.VerifyData(data, sig2, HashAlgorithmName.SHA1); Assert.True(verified); // Verify with no private key using (ECDsa ec3 = ECDsaFactory.Create()) { ec3.ImportParameters(ec2.ExportExplicitParameters(false)); Assert.Equal(ec2.KeySize, ec3.KeySize); verified = ec3.VerifyData(data, sig1, HashAlgorithmName.SHA1); Assert.True(verified); } } // Ensure negative result unchecked { sig1[sig1.Length - 1]++; } verified = ec1.VerifyData(data, sig1, HashAlgorithmName.SHA1); Assert.False(verified); } }
public static void DiminishedCoordsRoundtrip() { ECParameters toImport = EccTestData.GetNistP521DiminishedCoordsParameters(); ECParameters privateParams; ECParameters publicParams; using (ECDsa ecdsa = ECDsaFactory.Create()) { ecdsa.ImportParameters(toImport); privateParams = ecdsa.ExportParameters(true); publicParams = ecdsa.ExportParameters(false); } ComparePublicKey(toImport.Q, privateParams.Q); ComparePrivateKey(toImport, privateParams); ComparePublicKey(toImport.Q, publicParams.Q); Assert.Null(publicParams.D); }
internal static void FromXml(this ECDsa ecdsa, string xmlString) { if (string.IsNullOrEmpty(xmlString)) { throw new ArgumentException("Value cannot be null or empty.", nameof(xmlString)); } var parameters = new ECParameters { Q = new ECPoint() }; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlString); // ReSharper disable once PossibleNullReferenceException if (xmlDoc.DocumentElement.Name.Equals("ECDsaKeyValue")) { foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { switch (node.Name) { case "FriendlyName": parameters.Curve = ECCurve.CreateFromFriendlyName(node.InnerText); break; case "Q.X": parameters.Q.X = string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText); break; case "Q.Y": parameters.Q.Y = string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText); break; } } } else { throw new SerializationException($"Could not read {nameof(ECDsa)} parameters from the specified XML string."); } ecdsa.ImportParameters(parameters); }
public static void ImportExplicitWithHashButNoSeed() { if (!ECDsaFactory.ExplicitCurvesSupported) { return; } using (ECDsa ec = ECDsaFactory.Create()) { ECCurve curve = EccTestData.GetNistP256ExplicitCurve(); Assert.NotNull(curve.Hash); ec.GenerateKey(curve); ECParameters parameters = ec.ExportExplicitParameters(true); Assert.NotNull(parameters.Curve.Hash); parameters.Curve.Seed = null; ec.ImportParameters(parameters); ec.Exercise(); } }
private static void Validate( ECParameters parameters, ECCurve explicitCurve, byte[] msg, byte[] signature, HashAlgorithmName hashAlgorithm) { byte[] tamperedSignature = (byte[])signature.Clone(); tamperedSignature[0] ^= 0xFF; using (ECDsa ecdsa = ECDsaFactory.Create()) { ecdsa.ImportParameters(parameters); Assert.True( ecdsa.VerifyData(msg, signature, hashAlgorithm), "named verifies signature"); Assert.False( ecdsa.VerifyData(msg, tamperedSignature, hashAlgorithm), "named verifies tampered"); } if (ECDsaFactory.ExplicitCurvesSupported) { using (ECDsa ecdsa = ECDsaFactory.Create()) { parameters.Curve = explicitCurve; ecdsa.ImportParameters(parameters); Assert.True( ecdsa.VerifyData(msg, signature, hashAlgorithm), "explicit verifies signature"); Assert.False( ecdsa.VerifyData(msg, tamperedSignature, hashAlgorithm), "explicit verifies tampered"); } } }
public static void TestNamedCurves(CurveDef curveDef) { if (!curveDef.Curve.IsNamed) { return; } using (ECDsa ec1 = ECDsaFactory.Create(curveDef.Curve)) { ECParameters param1 = ec1.ExportParameters(curveDef.IncludePrivate); VerifyNamedCurve(param1, ec1, curveDef.KeySize, curveDef.IncludePrivate); using (ECDsa ec2 = ECDsaFactory.Create()) { ec2.ImportParameters(param1); ECParameters param2 = ec2.ExportParameters(curveDef.IncludePrivate); VerifyNamedCurve(param2, ec2, curveDef.KeySize, curveDef.IncludePrivate); AssertEqual(param1, param2); } } }
public static byte[] ECDsaSignHash(BigInteger privateKey, byte[] hash) { if (!IsPrivateKeyValid(privateKey)) { throw new Exception("privateKey is invalid."); } ECDsa ecdsa = ECDsa.Create(ECCurve.CreateFromFriendlyName("secp256k1")); // windows 10: https://docs.microsoft.com/en-us/windows/desktop/SecCNG/cng-named-elliptic-curves ECParameters parameters = ecdsa.ExportExplicitParameters(true); parameters.D = Encode.BigIntegerToBytes(privateKey, 32); // parameters.Q is not used in SignHash ecdsa.ImportParameters(parameters); while (true) { byte[] sig = ecdsa.SignHash(hash); // 64 bytes if (sig[32] < 0x7f) // low s value { return(sig); } } }
public override void ImportParameters(ECParameters parameters) => _impl.ImportParameters(parameters);
public void UseAfterDispose_Import(ECDsa ecdsa) { ecdsa.ImportParameters(EccTestData.GetNistP256ReferenceKey()); UseAfterDispose(ecdsa); }